Top of document
©Copyright 1999 Rogue Wave Software

Using Allocators with Existing Standard Library Containers

Using allocators with existing Standard C++ Library container classes is a simple process. Merely provide an allocator type when you instantiate a container, and provide an actual allocator object when you construct a container object:

All standard containers default the allocator template parameter type to allocator 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 will be used for all storage management.

If you do provide a different allocator type as a template parameter, then the type of object that you provide must match the template type. For example, the following code will cause an compiler error because the types in the template signature and the call to the allocator constructor don't match:

class my_allocator;
 list <int, allocator> my_list(my_allocator());   \\ Wrong!
 

The following call to the allocator constructor does match the template signature:

list <int, my_allocator> my_list(my_allocator());
 

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.


Top of document