本篇文章基于源码来剖析标准库中内存分配器的实现原理及使用。
说明一下,我用的是gcc7.1.0编译器,标准库源代码也是这个版本的。
还是来先通过思维导图来看一下本篇文章会从哪些方面来讲解stl中内存分配器和萃取器,如下:
其实stl中有关内存申请的操作是包含两个内容的:内存分配器、内存萃取器。
一、vector容器中对内存分配器的使用
前面的文章中说了,vector容器本质上是个动态数组,它其实就是使用标准库的内存分配器实现的,还是先看一下代码,如下:
template<typename _Tp, typename _Alloc>
struct _Vector_base
{
typedef typename __gnu_cxx::__alloc_traits<_Alloc>::template
rebind<_Tp>::other _Tp_alloc_type;
typedef typename __gnu_cxx::__alloc_traits<_Tp_alloc_type>::pointer
pointer;
struct _Vector_impl
: public _Tp_alloc_type
{
...
};
...
public:
_Vector_impl _M_impl;
pointer
_M_allocate(size_t __n)
{
typedef __gnu_cxx::__alloc_traits<_Tp_alloc_type> _Tr;
return __n != 0 ? _Tr::allocate(_M_impl, __n) : pointer();
}
...
};
class vector : protected _Vector_base<_Tp, _Alloc>
{
...};
vector继承于_Vector_base
,而_Vector_base
中内存分配又是结构体_Vector_impl
实现的,这个结构体继承于_Tp_alloc_type
,类型_Tp_alloc_type
的完整类型是__gnu_cxx::__alloc_traits<_Alloc>::template rebind<_Tp>::other
,而根据函数_M_allocate
最终实现内存分配是通过这样一个方式实现的,如下:
__gnu_cxx::__alloc_traits<_Tp_alloc_type>::allocate<