c++memory-managementallocator

Is it possible to have a stack allocator that contains a buffer?


I'm trying to implement a stack allocator that would work with std::vector. There are plenty of already existing implementations like this or this. However, all of them assume the buffer is not a member, but is provided to the allocator by the user. A comment in chromium's implementation even says that:

STL likes to make copies of allocators, so the allocator itself can't hold the data.

I tried myself and vector is crashing in its destructor. It seems that it creates a temporary version of my allocator for container proxy, allocates memory through that, and immediately destroys it, making a pointer to allocated data a dangling one.

Is it actually possible to have an allocator that stores a static buffer as a member?


Solution

  • Is it actually possible to have an allocator that stores a static buffer as a member?

    If the allocator is supposed to satisfy the Allocator standard library concept that is required by allocator-aware containers (and other utilities) in the standard library, then no, the memory resource itself cannot be embedded in the allocator object.

    One of the requirements is that an allocator object can be freely copy-constructed and the copied allocator object must be able to deallocate memory allocated by the original. Destroying the allocator object itself also must not cause the memory resource to vanish as long as a copy still exists.

    So, there needs to be an indirection. Either the user manages the lifetime of the memory resource and the allocator object holds a non-owning pointer to it, or you can use a shared_ptr to the memory resource so all copies of the allocator object jointly own the memory resource. However, this of course doesn't allow stack ownership.