Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can std::list have an allocator of type T?

I'm trying to implement my own standard compliant linked list and I can't seem to figure out why you'd ever want a T allocator. In my implementation, the node class holds the T itself, not a pointer to the T stored somewhere else in memory so T never gets explicitly allocated, instead it is only ever created as a part of the node. I would understand then why you might want a node allocator, but why a T?

A simplified version of my node here.

class Node {
    Node* next, prev;
    T data; // Not T*
}
like image 954
Keltek Avatar asked Sep 05 '25 03:09

Keltek


1 Answers

Welcome to the wonderful world of allocators! You are very correct with your observation, and this is why every allocator has to have a rebind type member in it.

This type allows allocator to convert the type it was instantiated with (T) to the allocator for the actual type which is allocated - something special for the lists or some other containers (maps, for example).

I personally believe a better solution would be to make allocators template template arguments, and allow container to get a concrete type - but at the time of STL design template template parameters were still not widely supported.

like image 175
SergeyA Avatar answered Sep 07 '25 19:09

SergeyA