以一个简单的例子开始。根据c++标准,std::allocator构建在::operator new()上。如果你正在使用一个自动化内存使用跟踪工具,让std::allocator更简单些会更方便。我们可以用malloc()代替::operator new(),而且我们也不考虑(在好的std::allocator实作中可以找到的)复杂的性能优化措施。我们将这个简单的allocator叫作malloc_allocator 。
既然malloc_allocator的内存管理很简单,我们就能将重点集中在所有stl的allocator所共有的样板上。首先,一些类型:allocator是一个类模板,它的实例专为某个类型t分配内存。我们提供了一序列的typedef,以描述该如何使用此类型的对象:value_type指t本身,其它的则是有各种修饰字的指针和引用。
template <class t> class malloc_allocator
{
public:
typedef t value_type;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
...
};
这些类型与stl容器中的很相似,这不是巧合:容器类常常直接从它的allocator提取这些类型。
为什么有这么多的typedef?你可能认为pointer是多余的:它就是value_type *。绝大部份时候这是对的,但你可能有时候想定义非传统的allocator,它的pointer是一个pointer-like的class,或非标的厂商特定类型value_type __far *;allocator是为非标扩展提供的标准hook。不寻常的pointer类型也是存在address()成员函数的理由,它在malloc_allocator中只是operator &()的另外一种写法:
template <class t> class malloc_allocator