C++ std::pmr Guide: Polymorphic Memory Resources & Memory Pools [#39-2]
이 글의 핵심
Inject memory resources into pmr containers to slash allocations in parsers, games, and servers.
Introduction: malloc dominates your profile
Pools & polymorphic allocators
Frequent small allocations fragment the heap and burn cycles. Memory pools pre-allocate slabs; C++17 std::pmr lets std::pmr::vector, std::pmr::string, etc. share std::pmr::memory_resource.
Topics: scenarios, monotonic_buffer_resource, synchronized_pool_resource, custom memory_resource, pmr containers, errors (lifetime!), alignment, benchmarks, production patterns (per-request arena, game frame).
monotonic_buffer_resource
Allocate forward-only; O(1) bump pointer; release/reset at scope end—ideal HTTP request or game frame scratch.
std::pmr::monotonic_buffer_resource pool;
std::pmr::vector<std::pmr::string> parts{&pool};
pool resources
unsynchronized_pool_resource / synchronized_pool_resource for many fixed-ish sizes with frees.
Custom memory_resource
Override do_allocate/do_deallocate/do_is_equal to plug jemalloc arenas, GPU pinned memory, etc.
Pitfalls
- Dangling:
pmrcontainers must not outlive theirmemory_resource. - Thread safety: unsynchronized resources require external sync.
- Alignment: respect
alignoffor over-aligned types.
Benchmarks
Compare default allocator vs pmr monotonic on representative parsers—expect fewer syscalls and better locality.
Full examples in this series also cover std::pmr::map in a request-handler style allocator setup.
Keywords
std::pmr, memory_resource, monotonic buffer, allocator, performance