allocator源码解析之malloc_allocator:
mt_allocator(待完成)
malloc_allocator 从名字看,难道是直接调用CRT(linux下为glibc)的的malloc和free函数,哇喔,这个allocator存在的意义是什么呢?
言归正传,malloc_allocator 源码位于:gcc-9.2.0/libstdc++-v3/include/ext/malloc_allocator.h,关键的allocator和deallocator函数的实现如下:
allocator实现:

allocator的实现确实如猜测,直接调用glibc相关的内存分配策略。
1)返回值同样为pointer,pointer的定义:
62 typedef _Tp* pointer;
2)核心代码第一个红框:108-109的两个预编译条件:(支持aligned_new, 同事cpp版本>201402L, 同时glibc有align_alloc的支持,同时瞒住110行的alignof(_Tp) > alignof(std::max_align_t) 会调用glibc的align_alloc版本
aligned_alloc 定义在cstdlib:void *aligned_alloc( size_t alignment, size_t size ),函数:按照alignment对齐方式,分配size大小的内存。该size参数必须是的整数倍alignment。
3)核心代码第二个红框:否则就直接调用glibc的malloc进行内存分配;
4)std::alignof c++11新增标识符: std::size_t alignof(type-id)
返回由type_id所指示的类型的任何实例所要求的对齐字节数
5)std::max_align_t 平台最大类型(一般为long double)的对齐大小,:
sizeof(std::max_align_t) = 32
alignof(std::max_align_t) = 16
alignof(long double) = 16
deallocate的函数定义:

没有任何意外 deallocate直接调用free去释放malloc的分配的空间;
总结:malloc_allocator没有任何惊喜,直接调用CRT环境的malloc和free,感觉一般不会用到,存在的价值是什么呢?
下一个分析pool_malloc, 看名字是有个pool,pool的实现希望能有惊喜;
网友评论