STL 的内存管理方式
在 C++ 中,使用 new/delete 方式进行对象内存管理分配和回收,底层分为两个步骤:
- new 操作步骤:1)调用::operator new 配置内存;2)调用对象的构造函数构造对象
- delete 操作步骤:1)调用对象析构函数;2)调用::operator delete 释放内存
而在 STL 中,将这个过程拆分为了两个独立的语句控制,即内存分配由空间配置器 alloc::allocate() / alloc::deallocate() 负责,对象构造由::construct() / ::destroy() 负责。而空间配置器根据异常处理方式、是否内置轻量内存池(应对内存碎片问题)、多线程下的内存分配处理(内存池的互斥访问)等的不同,分为了第一级配置器和第二级配置器
第一级配置器:__malloc_alloc_template
只是对系统 malloc, realloc, free 函数的简单封装,并考虑了分配失败后的异常处理情况
//异常处理/*tihs program is in the file of stl_alloc.h*///line 109 to 118class __malloc_alloc_template {private://内存不足异常处理static void* _S_oom_malloc(size_t);static void* _S_oom_realloc(void*, size_t);#ifndef __STL_STATIC_TEMPLATE_MEMBER_BUGstatic void (* __malloc_alloc_oom_handler)();#endif//line 141 to 146//指定自己的异常处理static void (* __set_malloc_handler(void (*__f)()))(){void (* __old)() = __malloc_alloc_oom_handler;__malloc_alloc_oom_handler = __f;return(__old);}//line 152 to 155#ifndef __STL_STATIC_TEMPLATE_MEMBER_BUGtemplate <int __inst>void (* __malloc_alloc_template<__inst>::__malloc_alloc_oom_handler)() = 0;#endif//line 41 to 50#ifndef __THROW_BAD_ALLOC# if defined(__STL_NO_BAD_ALLOC) || !defined(__STL_USE_EXCEPTIONS)# include <stdio.h># include <stdlib.h>//默认的强制退出# define __THROW_BAD_ALLOC fprintf(stderr, "out of memory\n"); exit(1)# else /* Standard conforming out-of-memory handling */# include <new>//抛出用户设计异常处理例程# define __THROW_BAD_ALLOC throw std::bad_alloc()# endif#endif
总的来说,就是留给用户异常处理接口和默认强制退出处理
第二级配置器:__default_alloc_template
这是 STL 容器的默认配置器。
相比较于第一级配置器,增加了轻量级的内存池和多线程环境下内存池的互斥访问(加锁)。当申请的内存大于 128bytes 时移交给第一级配置器处理,而小内存则利用内存池管理分配和回收。![Image [2].png](/uploads/projects/u26617090@vagux7/0fc4cdc19a02733aff31324d3944dfab.png)
内存池是利用链表结构实现的,每个链表节点的大小为 8bytes,每次申请的小内存都会调整为8的倍数。当 free_list 的空间足够时,直接分配。当空间不足时,调用 refill() 从 heap 内存中重新申请小内存。当释放空间时,会把小内存重新链接到 free_list 中
allocate() 流程
- 判断用户申请的空间大于 128bytes,调用第一级配置器分配空间
- 若小于等于 128bytes,则检查 free_list,如果有可用区块(每个区块 8bytes),则直接使用,否则调用 refill() 申请新空间
/* __n must be > 0 */static void* allocate(size_t __n){void* __ret = 0;if (__n > (size_t) _MAX_BYTES) {__ret = malloc_alloc::allocate(__n);//内存大于128时,采用第一级配置器处理}else {_Obj* __STL_VOLATILE* __my_free_list= _S_free_list + _S_freelist_index(__n);// Acquire the lock here with a constructor call.// This ensures that it is released in exit or during stack// unwinding.# ifndef _NOTHREADS/*REFERENCED*/_Lock __lock_instance;# endif_Obj* __RESTRICT __result = *__my_free_list;if (__result == 0)//若自由链表free_list不存在可用的区块,则从内存池中填充自由链表__ret = _S_refill(_S_round_up(__n));else {//若自由链表free_list存在可用区块,调整free_list*__my_free_list = __result -> _M_free_list_link;__ret = __result;}}return __ret;};
deallocate() 流程
- 判断回收的内存空间大于 128bytes,调用第一级配置器,最终会使用 free() 函数释放该内存空间
- 小于等于 128bytes,将其放回到 free_list
/* __p may not be 0 */static void deallocate(void* __p, size_t __n){if (__n > (size_t) _MAX_BYTES)//内存大于128时,采用第一级配置器处理malloc_alloc::deallocate(__p, __n);else {//否则,找到相应的自由链表位置,将其回收_Obj* __STL_VOLATILE* __my_free_list= _S_free_list + _S_freelist_index(__n);_Obj* __q = (_Obj*)__p;// acquire lock# ifndef _NOTHREADS/*REFERENCED*/_Lock __lock_instance;# endif /* _NOTHREADS */__q -> _M_free_list_link = *__my_free_list;*__my_free_list = __q;// lock is released here}}
construct() 和 destroy()
construct() 负责对象的构造,而 destroy() 负责对象的析构,二者都不进行内存空间的操作
uninitialized_copy(),uninitialized_fill()和uninitialized_fill_n()
- uninitialized_copy() 负责向未初始化的内存空间拷贝填充某个已有数据
- uninitialized_fill() 负责向未初始化的内存空间填充某个初值
- uninitialized_fill_n() 负责向未初始化的内存空间填充n个初值
#ifndef __SGI_STL_INTERNAL_UNINITIALIZED_H#define __SGI_STL_INTERNAL_UNINITIALIZED_H__STL_BEGIN_NAMESPACE// uninitialized_copy// Valid if copy construction is equivalent to assignment, and if the// destructor is trivial.template <class _InputIter, class _ForwardIter>/*该函数接受三个迭代器参数:迭代器first是输入的起始地址,*迭代器last是输入的结束地址,迭代器result是输出的起始地址*即把数据复制到[result,result+(last-first)]这个范围*为了提高效率,首先用__VALUE_TYPE()萃取出迭代器result的型别value_type*再利用__type_traits判断该型别是否为POD型别*/inline _ForwardIteruninitialized_copy(_InputIter __first, _InputIter __last,_ForwardIter __result){return __uninitialized_copy(__first, __last, __result,__VALUE_TYPE(__result));}template <class _InputIter, class _ForwardIter, class _Tp>inline _ForwardIter/*利用__type_traits判断该型别是否为POD型别*/__uninitialized_copy(_InputIter __first, _InputIter __last,_ForwardIter __result, _Tp*){typedef typename __type_traits<_Tp>::is_POD_type _Is_POD;return __uninitialized_copy_aux(__first, __last, __result, _Is_POD());}template <class _InputIter, class _ForwardIter>_ForwardIter //若不是POD型别,就派送到这里__uninitialized_copy_aux(_InputIter __first, _InputIter __last,_ForwardIter __result,__false_type){_ForwardIter __cur = __result;__STL_TRY {//这里加入了异常处理机制for ( ; __first != __last; ++__first, ++__cur)_Construct(&*__cur, *__first);//构造对象,必须是一个一个元素的构造,不能批量return __cur;}__STL_UNWIND(_Destroy(__result, __cur));//析构对象}template <class _InputIter, class _ForwardIter>inline _ForwardIter //若是POD型别,就派送到这里__uninitialized_copy_aux(_InputIter __first, _InputIter __last,_ForwardIter __result,__true_type){/*调用STL的算法copy()*函数原型:template< class InputIt, class OutputIt >* OutputIt copy( InputIt first, InputIt last, OutputIt d_first );*/return copy(__first, __last, __result);}//下面是针对char*,wchar_t* 的uninitialized_copy()特化版本inline char* uninitialized_copy(const char* __first, const char* __last,char* __result) {/* void* memmove( void* dest, const void* src, std::size_t count );* dest指向输出的起始地址* src指向输入的其实地址* count要复制的字节数*/memmove(__result, __first, __last - __first);return __result + (__last - __first);}inline wchar_t*uninitialized_copy(const wchar_t* __first, const wchar_t* __last,wchar_t* __result){memmove(__result, __first, sizeof(wchar_t) * (__last - __first));return __result + (__last - __first);}// Valid if copy construction is equivalent to assignment, and if the// destructor is trivial.template <class _ForwardIter, class _Tp>/*若是POD型别,则调用此函数*/inline void__uninitialized_fill_aux(_ForwardIter __first, _ForwardIter __last,const _Tp& __x, __true_type){/*函数原型:template< class ForwardIt, class T >* void fill( ForwardIt first, ForwardIt last, const T& value );*/fill(__first, __last, __x);}template <class _ForwardIter, class _Tp>/*若不是POD型别,则调用此函数*/void__uninitialized_fill_aux(_ForwardIter __first, _ForwardIter __last,const _Tp& __x, __false_type){_ForwardIter __cur = __first;__STL_TRY {for ( ; __cur != __last; ++__cur)_Construct(&*__cur, __x);}__STL_UNWIND(_Destroy(__first, __cur));}template <class _ForwardIter, class _Tp, class _Tp1>//用__type_traits技术判断该型别是否为POD型别inline void __uninitialized_fill(_ForwardIter __first,_ForwardIter __last, const _Tp& __x, _Tp1*){typedef typename __type_traits<_Tp1>::is_POD_type _Is_POD;__uninitialized_fill_aux(__first, __last, __x, _Is_POD());}template <class _ForwardIter, class _Tp>/*该函数接受三个参数:*迭代器first指向欲初始化的空间起始地址*迭代器last指向欲初始化的空间结束地址*x表示初值*首先利用__VALUE_TYPE()萃取出迭代器first的型别value_type*然后用__type_traits技术判断该型别是否为POD型别*/inline void uninitialized_fill(_ForwardIter __first,_ForwardIter __last,const _Tp& __x){__uninitialized_fill(__first, __last, __x, __VALUE_TYPE(__first));}// Valid if copy construction is equivalent to assignment, and if the// destructor is trivial.template <class _ForwardIter, class _Size, class _Tp>inline _ForwardIter/*若是POD型别,则调用此函数*/__uninitialized_fill_n_aux(_ForwardIter __first, _Size __n,const _Tp& __x, __true_type){/*调用STL算法*原型:template< class OutputIt, class Size, class T >* void fill_n( OutputIt first, Size count, const T& value );* template< class OutputIt, class Size, class T >* OutputIt fill_n( OutputIt first, Size count, const T& value );*/return fill_n(__first, __n, __x);}template <class _ForwardIter, class _Size, class _Tp>_ForwardIter/*若不是POD型别,则调用此函数*/__uninitialized_fill_n_aux(_ForwardIter __first, _Size __n,const _Tp& __x, __false_type){_ForwardIter __cur = __first;__STL_TRY {for ( ; __n > 0; --__n, ++__cur)_Construct(&*__cur, __x);return __cur;}__STL_UNWIND(_Destroy(__first, __cur));}template <class _ForwardIter, class _Size, class _Tp, class _Tp1>inline _ForwardIter//用__type_traits技术判断该型别是否为POD型别__uninitialized_fill_n(_ForwardIter __first, _Size __n, const _Tp& __x, _Tp1*){typedef typename __type_traits<_Tp1>::is_POD_type _Is_POD;//_Is_POD()判断value_type是否为POD型别return __uninitialized_fill_n_aux(__first, __n, __x, _Is_POD());}template <class _ForwardIter, class _Size, class _Tp>inline _ForwardIter/*该函数接受三个参数:*迭代器first指向欲初始化的空间起始地址*n表示欲初始化空间大小*x表示初值*首先利用__VALUE_TYPE()萃取出迭代器first的型别value_type*然后用__type_traits技术判断该型别是否为POD型别*/uninitialized_fill_n(_ForwardIter __first, _Size __n, const _Tp& __x){//__VALUE_TYPE(__first)萃取出first的型别value_typereturn __uninitialized_fill_n(__first, __n, __x, __VALUE_TYPE(__first));}__STL_END_NAMESPACE#endif /* __SGI_STL_INTERNAL_UNINITIALIZED_H */// Local Variables:// mode:C++// End:
