c++ 9.2.0 . allocator(1)new_allocator

allocator源码解析之new_allocator:

new_allocator

malloc_allocator

pool_allocator

bitmap_allocator

mt_allocator(待完成)


new_allocator是ST容器默认的allocator,通过分析源码深入了解allocator机制;

allocator负责STL组件和容器(大部分)的内存分配,默默的工作,例如,vector的定义:template< class T, class Allocator =std::allocator<T>> class vector;  

STL容器默认使用的allocator 为 std::allocator,   这个allocator定义在<memory> ,但具体的头文件在:#include <bits/allocator.h>,对应源码的位置:gcc-9.2.0/libstdc++-v3/include/bits/allocator.h中,代码中关于allocator的定义如下:

但类:__allocator_base的定义在gcc的代码中没找到, 查看该include头文件:

46 #include <bits/c++allocator.h> // Define the base class to std::allocator.   这个头文件不在gcc的代码里而是在和平台相关的代码部分:include/c++/9/x86_64-redhat-linux/bits/c++allocator.h ,c++allocator.h 相关行:

到此终于找到了allocator实现__allocator_base ,__allocator_base 是__gnu_cxx::new_allocator的类型别名,__gnu_cxx::new_allocator定义在:gcc-9.2.0/libstdc++-v3/include/ext/new_allocator.h中:

allocator 比较关键的两个函数:allocate(分配)和deallocate(回收)

allocate的函数:

从代码中111行和114行可以直接看出:new_allocator直接调用c++全局::operaotor new  实现的内存分配,没有任何额外操作。 只是分别调用不同的operator new重载版本

deallocate的函数实现:

从代码124行和128行可以看出,new_allocator直接调用c++全局::operator delete回收内存,没有任何额外的操作。

总结:从allocator实现可以看出, STL容器或者组件默认的allocator没有任何的优化,直接调用c++全局的operator new 和operator delete分配和回收内存。

额外知识点:

1)operator new和operator delete是c++默认的内存分配和回收的函数, 可以被重载(全局重载和类成员函数重载)

2)::operator new 和::operator delete 强制调用全局函数;

3) 模板类型别名,c++11特性; template<typename _Tp> using __allocator_base = __gnu_cxx::new_allocator<_Tp>; 例如:

template<typenameT>   

using Vec=std::vector<T,MyAlloc<T>>;

 Vec<int>coll;      //语句1

std::vector<int,MyAlloc<int>>coll; //语句2

语句1和语句2 意义相同

4)__STDCPP_DEFAULT_NEW_ALIGNMENT_  定义大小为:16

5)   std::align_val_t 类型的定义在<new>头文件中:

enum class align_val_t : std::size_t {};  

原因是operator new 以size_t为附加参数的重载已经有,所以用align_val_t 代替;

发现gcc-9.2.0/libstdc++-v3/include/ext/目录下还有其它的allocator:

打算逐一看看,加深对allocator的理解:

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。