Search code examples
c++templatescontainersallocator

Why are allocators to containers passed as template parameters?


Particularly, why do we have

template<typename T, typename A = allocator<T>>
class vector
{
    A alloc;
    //...
};

instead of

template<typename T>
class vector
{
    allocator<T> alloc;
    //...
};  

I saw this in a C++ manual and it confused me quite a bit. What other kinds of allocators could one possibly want/need?


Solution

  • Because this would work with only one allocator - standard one. But what if you want to allocate memory differently? For example, you might want to use shared memory, or file-backed memory, or anything else.

    This is the whole point of having allocators - to allow user to customize the way memory is going to be allocated and freed.