看到过几次,但一直对allocator
的功能不甚了解。最近在看《Effective STL》的时候,看到里面提到了allocator
以及示例代码,决定尝试去理解一下。
allocator
本质是:在每个新的对象实例被加入到容器中时,容器所作的准备工作。如果你以为新添加对象实例时,容器只需要在insert
函数中确认一下空间并new
一个对象,那就大错特错了。
以list
为例,容器在新添加对象的时候,除了为对象保留足够的空间外,还需要创建指向上个结点与下个结点的指针。这种在每次添加新对象实例时都具备的重复工作,就由allocator
完成。
我用User-Defined Allocator中的代码进行了测试。PS:这段代码太棒了,不足百行,简单清晰地演示了一般allocator
需要完成的工作。
//自定义的allocator
namespace MyLib {
template <class T>
class MyAlloc {
public:
// type definitions
typedef T value_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
// rebind allocator to type U
template <class U>
struct rebind {
typedef MyAlloc<U> other;
};
// return address of values
pointer address(reference value) const {
return &value;
}
const_pointer address(const_reference value) const {
return &value;
}