Using Custom Allocators
The STL and STL extension-based classes now accept an additional template allocator argument. The allocator argument has a default value of std::allocator<T> derived from the Standard C++ Library.
The use of custom allocators depends on the ANSI compliance of your compiler and your Standard C++ Library implementation. If allocators can be used, you can also provide your own allocator to customize memory management in an application.
In order to provide your own class template as an allocator, the template must conform to the particular interface described by the Standard C++ Library. This consists of member functions and typedefs as well as their syntactic and semantic requirements.
Here is a partial code snippet of a simple allocator:
template <class T>
class my_allocator
{
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
template <class U>
struct rebind { typedef allocator<U> other; };
// remaining member functions described below
// ...
};
The rebind member allows a container to construct an allocator for some arbitrary datatype. The allocator type is determined by the template parameter.
For example, a container may need to allocate types other than T (i.e. list nodes or hash buckets). In this case the container could obtain correct type, typically with a typedef:
typedef A::rebind<Node>::other Node_Allocator;
User-defined allocators must also be equality comparable; if a and b are instances of a user-defined allocator, then the expressions (a == b) and (a != b) must be well-formed.