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 函数的简单封装,并考虑了分配失败后的异常处理情况

  1. //异常处理/*tihs program is in the file of stl_alloc.h*///line 109 to 118
  2. class __malloc_alloc_template {
  3. private://内存不足异常处理
  4. static void* _S_oom_malloc(size_t);
  5. static void* _S_oom_realloc(void*, size_t);
  6. #ifndef __STL_STATIC_TEMPLATE_MEMBER_BUG
  7. static void (* __malloc_alloc_oom_handler)();
  8. #endif
  9. //line 141 to 146
  10. //指定自己的异常处理
  11. static void (* __set_malloc_handler(void (*__f)()))()
  12. {
  13. void (* __old)() = __malloc_alloc_oom_handler;
  14. __malloc_alloc_oom_handler = __f;
  15. return(__old);
  16. }//line 152 to 155
  17. #ifndef __STL_STATIC_TEMPLATE_MEMBER_BUG
  18. template <int __inst>
  19. void (* __malloc_alloc_template<__inst>::__malloc_alloc_oom_handler)() = 0;
  20. #endif
  21. //line 41 to 50
  22. #ifndef __THROW_BAD_ALLOC
  23. # if defined(__STL_NO_BAD_ALLOC) || !defined(__STL_USE_EXCEPTIONS)
  24. # include <stdio.h>
  25. # include <stdlib.h>//默认的强制退出
  26. # define __THROW_BAD_ALLOC fprintf(stderr, "out of memory\n"); exit(1)
  27. # else /* Standard conforming out-of-memory handling */
  28. # include <new>//抛出用户设计异常处理例程
  29. # define __THROW_BAD_ALLOC throw std::bad_alloc()
  30. # endif
  31. #endif

总的来说,就是留给用户异常处理接口和默认强制退出处理

第二级配置器:__default_alloc_template

这是 STL 容器的默认配置器。
相比较于第一级配置器,增加了轻量级的内存池和多线程环境下内存池的互斥访问(加锁)。当申请的内存大于 128bytes 时移交给第一级配置器处理,而小内存则利用内存池管理分配和回收。
Image [2].png

内存池是利用链表结构实现的,每个链表节点的大小为 8bytes,每次申请的小内存都会调整为8的倍数。当 free_list 的空间足够时,直接分配。当空间不足时,调用 refill() 从 heap 内存中重新申请小内存。当释放空间时,会把小内存重新链接到 free_list 中

allocate() 流程

  1. 判断用户申请的空间大于 128bytes,调用第一级配置器分配空间
  2. 若小于等于 128bytes,则检查 free_list,如果有可用区块(每个区块 8bytes),则直接使用,否则调用 refill() 申请新空间
  1. /* __n must be > 0 */
  2. static void* allocate(size_t __n)
  3. {
  4. void* __ret = 0;
  5. if (__n > (size_t) _MAX_BYTES) {
  6. __ret = malloc_alloc::allocate(__n);//内存大于128时,采用第一级配置器处理
  7. }
  8. else {
  9. _Obj* __STL_VOLATILE* __my_free_list
  10. = _S_free_list + _S_freelist_index(__n);
  11. // Acquire the lock here with a constructor call.
  12. // This ensures that it is released in exit or during stack
  13. // unwinding.
  14. # ifndef _NOTHREADS
  15. /*REFERENCED*/
  16. _Lock __lock_instance;
  17. # endif
  18. _Obj* __RESTRICT __result = *__my_free_list;
  19. if (__result == 0)//若自由链表free_list不存在可用的区块,则从内存池中填充自由链表
  20. __ret = _S_refill(_S_round_up(__n));
  21. else {//若自由链表free_list存在可用区块,调整free_list
  22. *__my_free_list = __result -> _M_free_list_link;
  23. __ret = __result;
  24. }
  25. }
  26. return __ret;
  27. };

deallocate() 流程

  1. 判断回收的内存空间大于 128bytes,调用第一级配置器,最终会使用 free() 函数释放该内存空间
  2. 小于等于 128bytes,将其放回到 free_list
  1. /* __p may not be 0 */
  2. static void deallocate(void* __p, size_t __n)
  3. {
  4. if (__n > (size_t) _MAX_BYTES)//内存大于128时,采用第一级配置器处理
  5. malloc_alloc::deallocate(__p, __n);
  6. else {//否则,找到相应的自由链表位置,将其回收
  7. _Obj* __STL_VOLATILE* __my_free_list
  8. = _S_free_list + _S_freelist_index(__n);
  9. _Obj* __q = (_Obj*)__p;
  10. // acquire lock
  11. # ifndef _NOTHREADS
  12. /*REFERENCED*/
  13. _Lock __lock_instance;
  14. # endif /* _NOTHREADS */
  15. __q -> _M_free_list_link = *__my_free_list;
  16. *__my_free_list = __q;
  17. // lock is released here
  18. }
  19. }

construct() 和 destroy()

construct() 负责对象的构造,而 destroy() 负责对象的析构,二者都不进行内存空间的操作

uninitialized_copy(),uninitialized_fill()和uninitialized_fill_n()

  • uninitialized_copy() 负责向未初始化的内存空间拷贝填充某个已有数据
  • uninitialized_fill() 负责向未初始化的内存空间填充某个初值
  • uninitialized_fill_n() 负责向未初始化的内存空间填充n个初值
  1. #ifndef __SGI_STL_INTERNAL_UNINITIALIZED_H
  2. #define __SGI_STL_INTERNAL_UNINITIALIZED_H
  3. __STL_BEGIN_NAMESPACE
  4. // uninitialized_copy
  5. // Valid if copy construction is equivalent to assignment, and if the// destructor is trivial.
  6. template <class _InputIter, class _ForwardIter>/*该函数接受三个迭代器参数:迭代器first是输入的起始地址,
  7. *迭代器last是输入的结束地址,迭代器result是输出的起始地址
  8. *即把数据复制到[result,result+(last-first)]这个范围
  9. *为了提高效率,首先用__VALUE_TYPE()萃取出迭代器result的型别value_type
  10. *再利用__type_traits判断该型别是否为POD型别
  11. */
  12. inline _ForwardIter
  13. uninitialized_copy(_InputIter __first, _InputIter __last,
  14. _ForwardIter __result){
  15. return __uninitialized_copy(__first, __last, __result,
  16. __VALUE_TYPE(__result));}
  17. template <class _InputIter, class _ForwardIter, class _Tp>
  18. inline _ForwardIter
  19. /*利用__type_traits判断该型别是否为POD型别*/__uninitialized_copy(_InputIter __first, _InputIter __last,
  20. _ForwardIter __result, _Tp*){
  21. typedef typename __type_traits<_Tp>::is_POD_type _Is_POD;
  22. return __uninitialized_copy_aux(__first, __last, __result, _Is_POD());}
  23. template <class _InputIter, class _ForwardIter>
  24. _ForwardIter //若不是POD型别,就派送到这里__uninitialized_copy_aux(_InputIter __first, _InputIter __last,
  25. _ForwardIter __result,
  26. __false_type){
  27. _ForwardIter __cur = __result;
  28. __STL_TRY {//这里加入了异常处理机制
  29. for ( ; __first != __last; ++__first, ++__cur)
  30. _Construct(&*__cur, *__first);//构造对象,必须是一个一个元素的构造,不能批量
  31. return __cur;
  32. }
  33. __STL_UNWIND(_Destroy(__result, __cur));//析构对象}
  34. template <class _InputIter, class _ForwardIter>
  35. inline _ForwardIter //若是POD型别,就派送到这里__uninitialized_copy_aux(_InputIter __first, _InputIter __last,
  36. _ForwardIter __result,
  37. __true_type){
  38. /*调用STL的算法copy()
  39. *函数原型:template< class InputIt, class OutputIt >
  40. * OutputIt copy( InputIt first, InputIt last, OutputIt d_first );
  41. */
  42. return copy(__first, __last, __result);}//下面是针对char*,wchar_t* 的uninitialized_copy()特化版本
  43. inline char* uninitialized_copy(const char* __first, const char* __last,
  44. char* __result) {/* void* memmove( void* dest, const void* src, std::size_t count );
  45. * dest指向输出的起始地址
  46. * src指向输入的其实地址
  47. * count要复制的字节数
  48. */
  49. memmove(__result, __first, __last - __first);
  50. return __result + (__last - __first);}
  51. inline wchar_t*
  52. uninitialized_copy(const wchar_t* __first, const wchar_t* __last,
  53. wchar_t* __result){
  54. memmove(__result, __first, sizeof(wchar_t) * (__last - __first));
  55. return __result + (__last - __first);}
  56. // Valid if copy construction is equivalent to assignment, and if the// destructor is trivial.
  57. template <class _ForwardIter, class _Tp>/*若是POD型别,则调用此函数
  58. */
  59. inline void
  60. __uninitialized_fill_aux(_ForwardIter __first, _ForwardIter __last,
  61. const _Tp& __x, __true_type){/*函数原型:template< class ForwardIt, class T >
  62. * void fill( ForwardIt first, ForwardIt last, const T& value );
  63. */
  64. fill(__first, __last, __x);}
  65. template <class _ForwardIter, class _Tp>/*若不是POD型别,则调用此函数
  66. */
  67. void
  68. __uninitialized_fill_aux(_ForwardIter __first, _ForwardIter __last,
  69. const _Tp& __x, __false_type){
  70. _ForwardIter __cur = __first;
  71. __STL_TRY {
  72. for ( ; __cur != __last; ++__cur)
  73. _Construct(&*__cur, __x);
  74. }
  75. __STL_UNWIND(_Destroy(__first, __cur));}
  76. template <class _ForwardIter, class _Tp, class _Tp1>//用__type_traits技术判断该型别是否
  77. 为POD型别
  78. inline void __uninitialized_fill(_ForwardIter __first,
  79. _ForwardIter __last, const _Tp& __x, _Tp1*){
  80. typedef typename __type_traits<_Tp1>::is_POD_type _Is_POD;
  81. __uninitialized_fill_aux(__first, __last, __x, _Is_POD());
  82. }
  83. template <class _ForwardIter, class _Tp>/*该函数接受三个参数:
  84. *迭代器first指向欲初始化的空间起始地址
  85. *迭代器last指向欲初始化的空间结束地址
  86. *x表示初值
  87. *首先利用__VALUE_TYPE()萃取出迭代器first的型别value_type
  88. *然后用__type_traits技术判断该型别是否为POD型别
  89. */
  90. inline void uninitialized_fill(_ForwardIter __first,
  91. _ForwardIter __last,
  92. const _Tp& __x){
  93. __uninitialized_fill(__first, __last, __x, __VALUE_TYPE(__first));}
  94. // Valid if copy construction is equivalent to assignment, and if the// destructor is trivial.
  95. template <class _ForwardIter, class _Size, class _Tp>
  96. inline _ForwardIter
  97. /*若是POD型别,则调用此函数
  98. */__uninitialized_fill_n_aux(_ForwardIter __first, _Size __n,
  99. const _Tp& __x, __true_type){
  100. /*调用STL算法
  101. *原型:template< class OutputIt, class Size, class T >
  102. * void fill_n( OutputIt first, Size count, const T& value );
  103. * template< class OutputIt, class Size, class T >
  104. * OutputIt fill_n( OutputIt first, Size count, const T& value );
  105. */
  106. return fill_n(__first, __n, __x);}
  107. template <class _ForwardIter, class _Size, class _Tp>
  108. _ForwardIter
  109. /*若不是POD型别,则调用此函数
  110. */__uninitialized_fill_n_aux(_ForwardIter __first, _Size __n,
  111. const _Tp& __x, __false_type){
  112. _ForwardIter __cur = __first;
  113. __STL_TRY {
  114. for ( ; __n > 0; --__n, ++__cur)
  115. _Construct(&*__cur, __x);
  116. return __cur;
  117. }
  118. __STL_UNWIND(_Destroy(__first, __cur));}
  119. template <class _ForwardIter, class _Size, class _Tp, class _Tp1>
  120. inline _ForwardIter
  121. //用__type_traits技术判断该型别是否为POD型别__uninitialized_fill_n(_ForwardIter __first, _Size __n, const _Tp& __x, _Tp1*){
  122. typedef typename __type_traits<_Tp1>::is_POD_type _Is_POD;
  123. //_Is_POD()判断value_type是否为POD型别
  124. return __uninitialized_fill_n_aux(__first, __n, __x, _Is_POD());}
  125. template <class _ForwardIter, class _Size, class _Tp>
  126. inline _ForwardIter
  127. /*该函数接受三个参数:
  128. *迭代器first指向欲初始化的空间起始地址
  129. *n表示欲初始化空间大小
  130. *x表示初值
  131. *首先利用__VALUE_TYPE()萃取出迭代器first的型别value_type
  132. *然后用__type_traits技术判断该型别是否为POD型别
  133. */uninitialized_fill_n(_ForwardIter __first, _Size __n, const _Tp& __x){
  134. //__VALUE_TYPE(__first)萃取出first的型别value_type
  135. return __uninitialized_fill_n(__first, __n, __x, __VALUE_TYPE(__first));}
  136. __STL_END_NAMESPACE
  137. #endif /* __SGI_STL_INTERNAL_UNINITIALIZED_H */
  138. // Local Variables:// mode:C++// End: