C++ - Allocators & pmr

Overview

Estimated time: 60–80 minutes

Control memory behavior with allocators. Use std::pmr polymorphic allocators and memory resources for performance-sensitive or bounded-allocation scenarios.

Learning Objectives

  • Understand classic allocator hooks and why pmr simplifies usage.
  • Use pmr containers with monotonic or unsynchronized_pool resource.

Prerequisites

pmr basics

#include 
#include 
#include 
#include 

int main(){
  std::pmr::monotonic_buffer_resource pool;
  std::pmr::vector v{ &pool };
  v.emplace_back("alpha", &pool);
  v.emplace_back("beta", &pool);
  for (auto& s: v) std::cout << s << "\n";
}

Custom buffer

#include 
#include 
#include 

int main(){
  std::array buf{};
  std::pmr::monotonic_buffer_resource pool(buf.data(), buf.size());
  std::pmr::vector v{ &pool };
  for (int i=0;i<100;++i) v.push_back(i);
}

Common Pitfalls

  • pmr containers do not own the resource—ensure resource outlives containers.
  • Monotonic resource never frees individual allocations; reset between phases.

Checks for Understanding

  1. When use pmr over default allocators?
  2. How to avoid dangling resource usage?
Show answers
  1. When you need custom allocation strategies, bounded arenas, or to reduce allocation overhead.
  2. Keep the memory_resource alive as long as pmr containers are in use.

Exercises

  1. Benchmark std::vector vs std::pmr::vector with a monotonic resource.
  2. Use an unsynchronized_pool_resource for many small allocations and compare performance.