STL提供了很多泛型容器,很多程序員是使用這些容器的時候都只關心何時往容器內塞對象,而不用關心如何管理內存,其實管理內存也是非常重要的,那么我們現在就去看看STL的內存管理。
1. 概述
STL Allocator是STL的內存管理器,也是最低調的部分之一,你可能使用了3年stl,但卻不知其為何物。
STL標準如下介紹Allocator
the STL includes some low-level mechanisms for allocating and deallocating memory. Allocators are very specialized, and you can safely ignore them for almost all purposes. Allocators encapsulate allocation and deallocation of memory. They provide a low-level interface that permits efficient allocation of many small objects; different allocator types represent different schemes for memory management.
<STL 源碼剖析>將其描述為空間配置器,理由是allocator可以將其它存儲介質(例如硬盤)做為stl 容器的存儲空間。由于內存是allocator管理的主要部分,因此,本文以STL內存管理為出發點介紹allocator。
Allocator就在我們身邊,通常使用STL的方式:
#include <vector>
std::vector<int> Array(100);
本質上,調用的是:
#include <vector>
std::vector<int, std::allocator> Array(100);
std::allocator就是一個簡單的Allocator
2. 使用
針對不同的應用場合,STL中實現了不同的Allocator,如下(gcc-3.4:http://www.cs.huji.ac.il/~etsman/Docs/gcc-3.4-base/libstdc++/html/20_util/allocator.html):
__gnu_cxx::new_allocator<T> Simply wraps ::operator new and ::operator delete.
__gnu_cxx::malloc_allocator<T> Simply wraps malloc and free. There is also a hook for an out-of-memory handler
__gnu_cxx::debug_allocator<T> A wrapper around an arbitrary allocator A. It passes on slightly increased size requests to A, and uses the extra memory to store size information.
__gnu_cxx::__pool_alloc<bool, int> A high-performance, single pool allocator. The reusable memory is shared among identical instantiations of this type.
__gnu_cxx::__mt_alloc<T> A high-performance fixed-size allocatorthat was initially developed specifically to suit the needs of multi threaded applications
__gnu_cxx::bitmap_allocato A high-performance allocator that uses a bit-map to keep track of the used and unused memory locations
例如,在多線程環境下,可以使用:
3.一個簡單的Allocator實現
我們可以實現自己的allocator
?
?
內存是allocator管理的主要部分,因此STL的內存管理也是非常重要的哦,如果你想了解更深一點的可以進入武林技術頻道進行了解哦。
新聞熱點
疑難解答
圖片精選