C++ Logo

std-proposals

Advanced search

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

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Mon, 25 Aug 2025 21:51:53 -0400
On Mon, Aug 25, 2025 at 9:17 PM Adrian Johnston via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
> Hello,
>
> I'd like to describe a scheme for managing allocators I have seen used
> in open world video games. It solves the same problems the
> pmr::polymorphic_allocator does in an easier way. This is not a
> request for a feature because I want it, I just think this scheme is
> more practical than the standard and would like to share it as such.
> This is intended for managing 1000s of allocations at once in a hard
> real-time environment where a general purpose allocator is too slow
> and is at risk of fragmenting.
>
> The idea is to have a thread local identifier for the "current
> allocator." Then an RAII class uses it to move all the code called
> within a certain scope into a selected allocator. This implements a
> stack of current allocators on the callstack. The previous allocator
> can be stored in the RAII object and so an explicit stack is not
> needed. In the same manner as the pmr code the current allocator's
> type is removed from the container's type signature entirely. The
> difference is that large quantities of code can be controlled without
> changing a line of it (or adding virtual operations everywhere.)

... I fail to see how this does what polymorphic_allocator does.

You have a functionally global allocator, and some RAII class that
sets the allocator on construction and unsets it on destruction. Then
you have other code that uses the current global allocator to allocate
and deallocate memory. This fundamentally binds allocation (and thus
deallocation) to a scope; if an allocation survives the destruction of
the RAII class that set the allocator, bad things happen.

Polymorphic allocator provides a non-template mechanism for individual
allocating objects to allocate memory in different ways. Which way it
is allocated is in no way associated with the current scope. As such,
an allocation can live however long the user wants to. There's no
implicit association of an allocation with a scope.

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?

Received on 2025-08-26 01:52:06