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.
Allocator就在我们身边,通常使用STL的方式:
#include
std::vector
#include
std::vector
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
__gnu_cxx::malloc_allocator
__gnu_cxx::debug_allocator
__gnu_cxx::__pool_alloc
__gnu_cxx::__mt_alloc
__gnu_cxx::bitmap_allocato A high-performance allocator that uses a bit-map to keep track of the used and unused memory locations
例如,在多线程环境下,可以使用:
复制代码 代码如下:
#include
#include
std::vector
3.一个简单的Allocator实现
我们可以实现自己的allocator
复制代码 代码如下:
#include
template
class my_allocator : public std::allocator
{
public:
typedef std::allocator
// 必须要重新定义
template
struct rebind
{
typedef my_allocator
};
// 内存的分配与释放可以实现为自定义的算法
pointer allocate(size_type count)
{
return (base_type::allocate(count));
}
void deallocate(pointer ptr, size_type count)
{
base_type::deallocate(ptr, count);
}
// 构造函数
my_allocator()
{}
my_allocator(my_allocator
{}
my_allocator
{
return (*this);
}
template
my_allocator(my_allocator
{}
template
my_allocator
{
return (*this); }
};



