C++空间分配器简述学习笔记
生活随笔
收集整理的這篇文章主要介紹了
C++空间分配器简述学习笔记
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
- 空間分配器 ? ? std:: allocator
? std::allocator提供的接口 ?---> ?位于頭文件<stl_alloc.h> ? 對象的定義和空間的分配是分開的。 template<typename T> class allocator { ? ?? ? ?typedef Alloc ?_alloc 實現層
?? public: ? ? ? ?//用來申請空間,分配新的空間
? ? ?? T * allocate(size_type n); ? ? ? ?//用來徹底回收空間 ? ? ? ?void deallocate(T *,size_type n); ? ? //在制定位置內存中,通過復制構造放入一個新元素
? ? ?? void ?construct(T * ,const T &_value); ? ? ? ?//只是銷毀對象,并不回收空間 ? ? ?? void destroy(T * ) ?? }
- 內存碎片: 內部碎片 和 外部碎片
STL采用了兩級空間配置器
- 當 < = 128字節的,采用內存池分配。
- > 128字節,直接malloc ? ? --->一級配置器??
- 一級配置器就是malloc 和free 的封裝 __malloc_alloc_template
- 二級配置器,__defaule_alloc_template?
-
- 內存池(堆空間),16個自由空閑鏈表存儲區,每一個都存儲著一個單鏈表的首地址(其中鏈表的每個節點都是8的倍數),從第一個開始一次是8的倍數,第一個就是8個字節,第二個是16字節,24,32,40,48,56,64,72,80,88,96,104,112,120,128、、最后一個是128字節,如果要獲取空間時,直接以O(1)的時間分配空間。
- 16個自由空閑鏈表 ? ---->數組,初始值時,都是空的
-
- static ?Obj* _S_free_list[16]
union Obj { ? ? ?union Obj * _M_free_list_link; ? ? ?char _M_CLIENT_DATA[1]; };
- 內存池
-
- static char ?* ? _S_start_free;
- static char ?*? ?_S_end_free;
- 從堆中獲取的最大空間
-
- static char ?*???_S_heap_size
函數:
- _S_free_list_index(size_t bytes); ?//找到相應字節大小的下標值
- _S_round_up(size_t bytes); ? ?//向上返回一個8的倍數
- _S_refill (size_t n);
- int nobjs=20; ? ?//一次性開辟20個相同n字節空間的塊。原理:以空間換時間。(因為alloc一般用于容器,避免了頻繁開空間)
- _S_chunk_alloc( n ,nobjs) ; ? //開辟空間的函數
-
- _total_byttes= n*nobjs=32*20=640;
- _bytes_left =_S_end_free - _S_start_free
- 初始時,沒有空間 ?, ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?bytes_to_get= 2*_totle_bytes=1280;
- _S_start_free=malloc(1280);
- _S_heap_size +=bytes_to_get;
-
- _total_byttes= n*nobjs=32*20=640;
- _bytes_left =_S_end_free - _S_start_free=1280
- _total_byttes= n*nobjs=32*20=640;
- _bytes_left =_S_end_free - _S_start_free=1280
- _S_refill( ); //劃分細化?
總結
以上是生活随笔為你收集整理的C++空间分配器简述学习笔记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vue学习—Convert HTML s
- 下一篇: 1、Flutter Widget(IOS