I am using a custom allocator, which has a small simple state internally. When I use it with std::vector
, I was surprised to see that get_allocator()
actually returns copy to the allocator.
This is documented here: http://en.cppreference.com/w/cpp/container/vector/get_allocator
What is the reason for this?
One reason I can imagine is that get_allocator
is a const
member, I wouldn't mind getting a const
reference to the allocator. Besided the internal allocator could have been declared mutable
.
Am I missing something?
Is there a workaround to get the internal allocator of std::vector<T, special_allocator<T>>
to inspect the state of the allocator?
Note: There is also the possibility that if the allocator is stateful then, perhaps one is supposed to use references all the way? Like std::vector<T, special_allocator<T>&>
Stateful allocators are supposed to copy with retaining their state.
For example, when you pass an allocator for a map, it is rebound to another allocator type, but still retains the state you've passed to it.
Or two distinct containers share allocator state, yet they have different allocator instance.
Typically, you have allocator that has pointer to your state. Make pointer to your state a parameter of allocator constructor, and pass it as a parameter of your container constructor.