Using allocators with existing Standard C++ Library container classes is a simple process. You just provide an allocator type when you instantiate a container, and provide an actual allocator object when you construct a container object:
my_allocator alloc<int>; // Construct an allocator vector<int,my_allocator<int> > v(alloc); // Use the allocator
All standard containers default the allocator template parameter type to allocator<T> and the object to Allocator(), where Allocator is the template parameter type. This means that the simplest use of allocators is to ignore them entirely. When you do not specify an allocator, the default allocator is used for all storage management.
If you do provide a different allocator type as a template parameter, the type of object that you provide must match the template type. For example, the following code will cause a compiler error because the types in the template signature and the call to the allocator constructor don't match:
template <class T> class my_alloc; list <int, allocator<int> > my_list(my_alloc()); \\ Wrong!
The following call to the allocator constructor does match the template signature:
list <int, my_alloc<int> > my_list(my_alloc());
It's also important that the type used for the allocator template parameter and the type used as the element type in a standard container agree. For instance:
list<int, allocator<long>> \\ Wrong!
won't work. Remember that with a map the contained type is actually a key-value pair:
map<int,long,less<int>,allocator<pair<int,long>>>
Note that the container always holds a copy of the allocator object that is passed to the constructor. If you need a single allocator object to manage all storage for a number of containers, you must provide an allocator that maintains a reference to some shared implementation.
OEM Edition, ©Copyright 1999, Rogue Wave Software, Inc.
Contact Rogue Wave about documentation or support issues.