CKTIS / C++
std::pmr::memory_resource — polymorphic memory resource
std::pmr::memory_resource is an abstract interface for allocating and deallocating storage with a specified alignment. It enables runtime selection of an allocation strategy, while std::pmr::polymorphic_allocator connects that interface to code expecting an allocator.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <memory_resource>
std::pmr::memory_resource* resource = std::pmr::new_delete_resource();
void* p = resource->allocate(bytes, alignment);
resource->deallocate(p, bytes, alignment);std::pmr::memory_resource, declared in <memory_resource>, represents a storage resource, not a typed allocator or container. It cannot be instantiated directly. std::pmr::polymorphic_allocator<T> uses a resource selected at runtime without changing its static type; it stores a resource pointer without taking ownership. The resource must remain available during operations that use it.
allocate(bytes, alignment) allocates at least bytes bytes with the requested alignment; alignment must be a power of two and defaults to alignof(std::max_align_t). This is not a general operation for invoking constructors of user-defined objects. Allocation failure is reported by an exception. deallocate(p, bytes, alignment) requires the same size and alignment and a block not previously deallocated, allocated through an equal resource. It does not invoke object destructors and must not throw exceptions.
The public functions delegate to the private pure virtual functions do_allocate, do_deallocate, and do_is_equal, which a derived class implements. The interface has a virtual destructor. is_equal(other) means that both resources can deallocate each other's allocations, not that they have identical configurations. operator== checks &a == &b || a.is_equal(b).
The example uses new_delete_resource(), a static-lifetime resource backed by ::operator new and ::operator delete. It allocates and deallocates a block without writing into it, then prints true because repeated calls to that function return the same resource. This entry targets C++23; the supplied working draft is a living document, not a frozen C++23 edition. The repository compiler flag does not establish production runtime compatibility.
Examples
#include <iostream>
#include <memory_resource>
int main() {
std::pmr::memory_resource* resource =
std::pmr::new_delete_resource();
void* p = resource->allocate(sizeof(int), alignof(int));
const bool equal = resource->is_equal(*std::pmr::new_delete_resource());
resource->deallocate(p, sizeof(int), alignof(int));
std::cout << std::boolalpha << equal << '\n';
}
Result
true
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.