C++ Logo

std-proposals

Advanced search

Re: [std-proposals] An RAII approach to polymorphic allocators

From: Jonathan Wakely <cxx_at_[hidden]>
Date: Tue, 26 Aug 2025 13:55:00 +0100
On Tue, 26 Aug 2025 at 02:52, Jason McKesson via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> On Mon, Aug 25, 2025 at 9:17 PM Adrian Johnston via Std-Proposals
> <std-proposals_at_[hidden]> wrote:
> What you seem to be talking about is an alternative to one specific
> polymorphic allocator; the `monotonic_buffer_resource` or arena
> allocator, which implicitly builds a stack of allocations and frees
> them all at once. But if you want that bound to a scope... you can
> just do that. Why does the standard need an object to do that?


The proposal also implies an alternative to
std::pmr::get_default_resource() which is not a global resource but is
thread-local.

You could copy the code for pmr::polymorphic_allocator and change the one
place where it uses pmr::get_default_resource() and change that to use
pmr::get_thread_local_resource(), and then provide
pmr::set_thread_local_resource() to set the current resource. But that
would still mean going via the pmr::memory_resource API with its virtual
functions. I think the intention is to avoid that, so you'd have N
different buffer resources and a thread-local ID which says which one to
use in any given scope. Then you could write a class template that meets
the Cpp17Allocator requirements and consults the thread-local ID to decide
where to (de)allocate memory.

The advantage over pmr::polymoprhic_allocator would be avoiding the virtual
functions for pmr::memory_resource, and not needing to pass a
pmr::memory_resource* to the pmr::polymorphic_allocator constructor,
because it would just use the current thread-local ID.

The disadvantage would be that it only supports one type of arena (which is
quite similar to the pmr::monotonic_buffer_resource) and so can't use other
allocation strategies. As mentioned, it would be fairly easy for containers
(and other objects) to refer to arenas that had gone out of scope, although
this is also possible with PMR if you aren't careful.

You could probably build this on top of a map of
pmr::monotonic_buffer_resource and make sure the compiler has enough type
info visible to de-virtualize the calls to the memory_resource members.

Received on 2025-08-26 12:55:19