Defining your own allocator is a relatively simple process. The C++ Standard Library describes a particular interface, consisting of types and functions. An allocator that conforms to the standard must match the syntactic requirements for these member functions and types. The C++ Standard Library also specifies a portion of the semantics for the allocator type.
An allocator that conforms to the C++ Standard Library allocator specification must have the following interface. The example uses my_allocator as a place holder for your own allocator name:
template <class T> class my_allocator { typedef unsigned integral type size_type; typedef signed integral type difference_type; typedef pointer to T pointer; typedef const pointer to T const_pointer; typedef T& reference; typedef const T& const_reference; typedef T value_type; template <class U> struct rebind { typedef allocator<U> other; }; };
The rebind member allows a container to construct an allocator for some arbitrary type out of the allocator type provided as a template parameter. For instance, the list container gets an allocator<T> by default, but a list may well need to allocate list_nodes as well as T's. The container can construct an allocator for list_nodes out of the allocator for T, which is the template parameter Allocator in this case, as follows:
Allocator::rebind<list_node>::other list_node_allocator;
Here is a description of the member functions that an allocator class template must provide:
my_allocator(); template <class U>
my_allocator(const my_allocator<U>&); template <class U>
Constructors.
~my_allocator();
Destructor.
operator=(const my_allocator<U>&);
Assignment operator.
pointer address(reference r) const;
Returns the address of r as a pointer type. This function and the following function are used to convert references to pointers.
const_pointer address(const_reference r) const;
Returns the address of r as a const_pointer type.
pointer allocate(size_type n, allocator<U>::const_pointer hint=0);
Allocates storage for n values of T. Uses the value of hint to optimize storage placement, if possible.
void deallocate(pointer);
Deallocates storage obtained by a call to allocate.
size_type max_size();
Returns the largest possible storage available through a call to allocate.
void construct(pointer p, const_reference val);
Constructs an object of type T at the location of p, using the value of val in the call to the constructor for T.
void destroy(pointer p);
Calls the destructor on the value pointed to by p.
Additionally, user-defined allocators must 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.