Site Tools


wiki:hpp-memory-resource

Table of Contents

<memory_resource>

<memory_resource> provides polymorphic memory allocators: std::pmr::memory_resource and standard containers adapted to use them, like std::pmr::vector, std::pmr::string. This allows switching allocators (stack, arena, monotonic) at runtime without changing container types.

Use it when you need custom allocation strategies; most code just uses the default allocator.

Example

This example uses a pmr vector with the default new_delete resource, demonstrating polymorphic memory allocation.

// compile: g++ -std=c++17 -o memoryresourceexample memoryresourceexample.cpp
// run: ./memoryresourceexample
// description: pmr vector with a memory resource
 
#include <memory_resource>
#include <vector>
#include <iostream>
 
int main() {
    std::vector<int, std::pmr::polymorphic_allocator<int>> vec(std::pmr::new_delete_resource());
    vec.push_back(1);
    vec.push_back(2);
 
    std::cout << "vec size: " << vec.size() << "\n";
 
    return 0;
}
wiki/hpp-memory-resource.md · Last modified: by 127.0.0.1