質問

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?

役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top