How to rebind a stateful allocator in C++?

568 views Asked by At

Assuming a situation where we have a stateful allocator and creating a copy is not desirable, I assume it would have to be supplied by reference (to any given struct or class), so:

element_allocator_type &allocator = supplied_allocator;

How does one rebind this allocator reference to another type without losing it's statefulness ie. without creating a copy? Can we in fact do so? If:

typedef typename std::allocator_traits<element_allocator_type>::template rebind_alloc<unsigned char> uchar_allocator_type;

(for example) is the type we're rebinding to, what is the line to create a rebinded allocator reference?

uchar_allocator_type &rebound_allocator = ???

Cheers-

1

There are 1 answers

2
Nicol Bolas On

Assuming that a stateful allocator has to be supplied by reference (to any given struct or class)

Well there's your problem. The C++ standard library allocator model requires no such thing. Allocator types are required to be copyable, even stateful ones. The expectation is that the copy of the allocator will behave like the original and memory allocated by one can be freed by the other (which is what == means when applied to two allocators).

In short, if your allocator is stateful, it must provide shallow copying behavior. And that's how you implement rebind: the new allocator may have a different allocation type, but it references the same allocation machinery.