Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::pmr::polymorphic_allocator — runtime memory-resource selection

std::pmr::polymorphic_allocator<T>, declared in <memory_resource>, routes memory requests to a std::pmr::memory_resource object. It lets allocation strategies vary at runtime without changing the allocator type or the container type that uses it.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <memory_resource>
std::pmr::polymorphic_allocator<T> alloc{resource_ptr};

std::pmr::polymorphic_allocator<T> holds a non-owning pointer to a std::pmr::memory_resource. The resource implements the allocation strategy through a virtual interface. Two allocators of the same type can therefore use different strategies. The pointer-taking constructor requires a value other than nullptr; the default constructor stores the result of std::pmr::get_default_resource().

allocate(n) requests storage for n elements of T, with suitable alignment, but does not call their constructors. deallocate(p, n) forwards the deallocation request to the selected memory resource without destroying any elements. The resource need not reclaim storage on an individual deallocation. A container manages these stages for you. construct supports uses-allocator construction for compatible nested types; this does not automatically make an ordinary type PMR-aware.

The allocator does not manage the resource's lifetime. The resource must remain alive during every operation that uses it, including container destruction. Copying the allocator itself preserves its resource pointer, but select_on_container_copy_construction() returns a default allocator: do not assume that ordinary container copying preserves the source resource.

The example explicitly passes the allocator to std::vector; std::pmr::vector<int> is shorthand for this container type. Declaration order ensures that the container is destroyed before the resource. std::pmr::monotonic_buffer_resource reclaims storage collectively rather than on each individual deallocation. Expected output is 30 and true on separate lines. This entry targets C++23 usage; the supplied live standard draft is not a frozen C++23 publication.

Examples

#include <iostream>
#include <memory_resource>
#include <vector>

int main() {
    std::pmr::monotonic_buffer_resource resource;
    std::pmr::polymorphic_allocator<int> alloc{&resource};
    std::vector<int, std::pmr::polymorphic_allocator<int>> values{alloc};

    values.push_back(10);
    values.push_back(20);

    std::cout << values[0] + values[1] << '\n';
    std::cout << std::boolalpha
              << (values.get_allocator().resource() == &resource) << '\n';
}

Result

30
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.

Sources