Alden Bernitt
Alden Bernitt

Reputation: 139

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?

Upvotes: 1

Views: 380

Answers (1)

SergeyA
SergeyA

Reputation: 62553

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.

Upvotes: 2

Related Questions