Is there a way, having one allocator object for type T, to use the SAME object to allocate memory for any other type. Maybe some magic with static_cast or rebind can help? Because right now I only have an idea of how to use rebind to derive the allocator type for the desired object type from the original allocator, but I don't understand how to use a ready-made allocator object to create any type of object.
CodePudding user response:
An allocator a
of type A
for value type T
conforming to the standard requirements can be rebound to an allocator for type U
via e.g.
std::allocator_traits<A>::rebind_alloc<U> b(a);
(although an allocator may support only a subset of all possible types U
and fail to instantiate with others)
Then b
can be used to allocate and deallocate objects of type U
. You do not need to store this allocator b
in addition to a
however. Each time you perform this rebind from the same value of a
it is guaranteed that the b
objects compare equal, meaning that one can be used to deallocate memory allocated by the other.
Note that I didn't say that correctly in a previous comment: It is not guaranteed that an allocation allocated by a
can be deallocated by b
. So an allocator may be using e.g. different memory resources for different types, but the memory resources cannot be embedded into the allocator and copied on allocator copy or rebind.