Reputation: 99
I notice that allocator can only allocate objects of type T
and reserve blocks of memory of size n * sizeof(T)
. Linked list nodes inside of the std::list<T>
type, however, aren't necessarily objects of type T
, nor are they necessarily the same size as T
objects. In that case, how can std::list
use std::allocator
to allocate memory?
Upvotes: 7
Views: 342
Reputation: 33437
This is why the rebind type exists. It allows you to create a similar allocator that instead allocates something else (like a node<T>
for example).
Basically like this:
std::allocator<int> int_alloc;
std::allocator<int>::rebind<node<int>> node_alloc;
//Perhaps more useful:
decltype(int_alloc)::rebind<node<int>> node_alloc;
Of course, in a real situation this would all be templated, but hopefully this shows the idea.
For more information, read the notes and examples here.
Upvotes: 5