Apache C++ Standard Library User's Guide

## 15.2 Using Allocators with Existing C++ Standard Library Containers

Using allocators with existing C++ Standard 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:

    template <class T> class my_allocator {...}; // Define an allocator
    my_allocator<int> alloc;                     // Construct instance
    std::vector<int,my_allocator<int> > v(alloc);// Use the allocator

All standard containers have a default allocator template of type `std::allocator<T>` and a default allocator constructor argument of type `allocator_type()`, where `allocator_type` is a typedef for the allocator template parameter. 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 the allocator argument passed to the container's constructor must either exactly match or be implicitly convertible to the allocator template parameter. For example, the following code will cause a compiler error because the types of the template parameter and the constructor argument don't match:

    template <class T> class my_allocator {...};

    std::list<int,std::allocator<int> >
      my_list(my_allocator<int>());                          // Wrong!

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

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

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:

    std::list<int, std::allocator<long> >                    // Wrong!

won't work. Remember that with a map the contained type is actually a key-value pair:

    std::map<int,long,std::less<int>,
             std::allocator<std::pair<const 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.