# Allocators and polymorphic memory resources

> An allocator tells a container where its memory comes from, and allocator_traits fills in everything the allocator leaves out. This page covers the minimal allocator, rebinding, the propagation traits that decide what copy, move and swap do with allocator state, and the std::pmr design that puts the memory source behind a virtual interface.

- **Source:** C++ Atlas (https://cppatlas.com/topics/allocators-and-pmr)
- **Track:** Memory model
- **Estimated reading time:** 15 minutes
- **ISO C++ clauses:** [allocator.requirements] (https://eel.is/c++draft/allocator.requirements), [allocator.traits] (https://eel.is/c++draft/allocator.traits), [default.allocator] (https://eel.is/c++draft/default.allocator), [container.reqmts] (https://eel.is/c++draft/container.reqmts), [container.alloc.reqmts] (https://eel.is/c++draft/container.alloc.reqmts), [mem.res] (https://eel.is/c++draft/mem.res), [mem.poly.allocator.class] (https://eel.is/c++draft/mem.poly.allocator.class), [mem.res.pool] (https://eel.is/c++draft/mem.res.pool), [mem.res.monotonic.buffer] (https://eel.is/c++draft/mem.res.monotonic.buffer), [allocator.uses] (https://eel.is/c++draft/allocator.uses), [allocator.adaptor] (https://eel.is/c++draft/allocator.adaptor)
- **cppreference links:** [Allocator named requirement](https://en.cppreference.com/w/cpp/named_req/Allocator), [std::allocator_traits](https://en.cppreference.com/w/cpp/memory/allocator_traits), [std::pmr::memory_resource](https://en.cppreference.com/w/cpp/memory/memory_resource), [std::pmr::polymorphic_allocator](https://en.cppreference.com/w/cpp/memory/polymorphic_allocator), [std::pmr::monotonic_buffer_resource](https://en.cppreference.com/w/cpp/memory/monotonic_buffer_resource), [std::pmr::unsynchronized_pool_resource](https://en.cppreference.com/w/cpp/memory/unsynchronized_pool_resource), [std::scoped_allocator_adaptor](https://en.cppreference.com/w/cpp/memory/scoped_allocator_adaptor), [std::allocator_traits::allocate_at_least](https://en.cppreference.com/w/cpp/memory/allocator_traits/allocate_at_least)
- **Prerequisites:** dynamic-allocation-new-and-delete, copy-and-move, sequence-containers

## The one idea

An allocator is a small value that a container stores and asks for memory. It is not the memory itself, and it is not a heap; it is a handle to one. Two allocators compare equal when memory obtained from one can be released through the other. Everything interesting about allocators follows from that: a container may only hand its buffer to another container whose allocator could free it.

The container never calls the allocator directly. It goes through `std::allocator_traits<A>`, which supplies a default for almost every member, so a usable allocator needs only a handful of declarations.

> **Mental model.** Think of an allocator as a library card. Containers with equal cards can trade books freely. Containers with different cards must copy the books, because each library only takes back its own. The propagation traits answer one question: when a container is copied, moved or swapped, does its card go with the books?

## The minimal allocator and allocator_traits

The Allocator requirements in [allocator.requirements] are written as a long table, but almost every row has a default in `allocator_traits`. What you must write is `value_type`, `allocate`, `deallocate`, equality, and a converting constructor from the same template with another element type.

```cpp
#include <cstddef>
#include <list>
#include <new>
#include <vector>

template <class T>
struct Mini {
  using value_type = T;
  Mini() = default;
  template <class U> Mini(const Mini<U>&) noexcept {}
  T* allocate(std::size_t n) { return static_cast<T*>(::operator new(n * sizeof(T))); }
  void deallocate(T* p, std::size_t n) noexcept { ::operator delete(p, n * sizeof(T)); }
};
template <class T, class U>
bool operator==(const Mini<T>&, const Mini<U>&) { return true; }

std::vector<int, Mini<int>> v{1, 2, 3};
std::list<int, Mini<int>> l{1, 2, 3};   // rebinds Mini<int> to Mini<node>
```

Since C++20 `operator!=` is synthesized from `operator==`. `allocator_traits` provides `pointer` as `value_type*`, `size_type`, `max_size`, `construct` through `std::construct_at`, `destroy` through `std::destroy_at`, the propagation traits as `false_type`, and `is_always_equal` as `std::is_empty<A>`. A stateless allocator is therefore treated as always equal without saying so.

`std::allocator<T>` is the default. C++20 removed its `construct`, `destroy` and `rebind` members, which `allocator_traits` provides anyway, and made it usable in constant evaluation.

### Rebinding

A `std::list<int, A>` never allocates an `int`. It allocates nodes that contain an `int` and two pointers. It obtains an allocator for nodes with `allocator_traits<A>::rebind_alloc<Node>`, which defaults to replacing the first template argument, so `Mini<int>` becomes `Mini<Node>`. Then it constructs that allocator from the one you passed, which is why the converting constructor is required.

Rebinding must preserve identity. An allocator and its rebound copy must compare equal both ways, meaning memory from either can be freed by the other. A stateful allocator therefore carries the same state, typically a pointer to an arena, through every rebind.

## Stateful allocators and the propagation traits

When allocators carry state, unequal allocators can coexist, and each container operation has to decide what to do with them. Three traits make the decision, plus one function for copies.

| Operation | Trait or function | If it says no and the allocators differ |
|---|---|---|
| copy construction | `select_on_container_copy_construction()` | the returned allocator is used, whatever it is |
| copy assignment | `propagate_on_container_copy_assignment` (POCCA) | keep the target's allocator, copy elements into its memory |
| move assignment | `propagate_on_container_move_assignment` (POCMA) | keep the target's allocator, move elements one by one |
| swap | `propagate_on_container_swap` (POCS) | undefined behavior |

Move construction has no trait. It always move-constructs the allocator from the source, so the new container can adopt the source's buffer in constant time.

The move-assignment case explains a surprise in the standard containers' signatures. When POCMA is true, the target frees its own memory with its old allocator, takes the source's allocator, and steals the buffer. When POCMA is false but the allocators compare equal, it can steal the buffer anyway. When POCMA is false and they compare unequal, the target's allocator cannot free the source's buffer, so the target must allocate its own memory and move-assign or move-construct each element. That can throw. So `vector`'s move assignment is declared `noexcept(POCMA || is_always_equal)`, and for allocators that are neither, it is not `noexcept`.

```cpp
#include <memory_resource>
#include <type_traits>
#include <vector>

static_assert(std::is_nothrow_move_assignable_v<std::vector<int>>);
static_assert(!std::is_nothrow_move_assignable_v<std::pmr::vector<int>>);
static_assert(std::is_nothrow_move_constructible_v<std::pmr::vector<int>>);
```

> **Standardese.** [container.reqmts] says that when POCS is false, `swap` does not exchange the allocators, and the behavior is undefined unless the two allocators compare equal. Swap is specified as constant time and non-throwing for containers other than `std::array`, so it cannot fall back to copying elements the way move assignment does.

`std::allocator` has POCMA true and is always equal, which is why ordinary containers never meet these cases.

## std::pmr: the resource behind a pointer

C++17's `std::pmr` moves the memory source out of the allocator's type and behind a virtual interface. `std::pmr::memory_resource` has public non-virtual `allocate`, `deallocate` and `is_equal`, which call the private virtual `do_allocate`, `do_deallocate` and `do_is_equal`. `std::pmr::polymorphic_allocator<T>` is a thin allocator that stores a `memory_resource*` and forwards to it. Containers in `std::pmr`, such as `std::pmr::vector<T>`, are aliases for the ordinary templates with that allocator, so containers using different resources have the same type.

The surprising part is that `polymorphic_allocator` never propagates. All three propagation traits are false, and `select_on_container_copy_construction` returns a default-constructed allocator, which uses the current default resource rather than the source's resource.

```cpp
#include <memory_resource>
#include <vector>

void copy_does_not_follow() {
  std::pmr::monotonic_buffer_resource arena;
  std::pmr::vector<int> a({1, 2, 3}, &arena);
  std::pmr::vector<int> b = a;
  // b.get_allocator().resource() == std::pmr::get_default_resource(), not &arena
}
```

The design reflects how resources are used. A resource is usually scoped: a monotonic arena on the stack for one request, a pool for one subsystem. An object's resource is decided when the object is constructed and then never changes. If copying or assigning propagated the resource, a long-lived container could silently start pointing at an arena about to be destroyed. The cost is that `b = std::move(a)` between different resources copies element by element and may throw.

> **Pitfall.** Returning a `std::pmr::vector` by value from a function, or copying one into a member, does not keep the arena it was built in. The copy goes to the default resource, which is usually `new_delete_resource()`. Pass the resource explicitly, as in `std::pmr::vector<int> b(a, &arena);`.

## The standard resources

The library provides two global resources and three classes.

- `std::pmr::new_delete_resource()` allocates with `::operator new` and is the initial default resource.
- `std::pmr::null_memory_resource()` throws `std::bad_alloc` from every allocation. As an upstream it turns "fell back to the heap" into an error.
- `std::pmr::monotonic_buffer_resource` hands out memory by bumping a pointer through an optional initial buffer, then through blocks of growing size obtained from its upstream. `deallocate` does nothing; everything is returned at once by `release()` or the destructor. It is not thread-safe.
- `std::pmr::unsynchronized_pool_resource` and `std::pmr::synchronized_pool_resource` keep pools of fixed-size blocks for a range of sizes and route larger requests to the upstream. The synchronized one may be used from several threads. `std::pmr::pool_options` tunes the largest pooled size and the chunk size.

`std::pmr::set_default_resource` changes what default-constructed polymorphic allocators use, for the whole program.

```cpp
#include <cstddef>
#include <memory_resource>
#include <vector>

int sum_small() {
  std::byte buf[1024];
  std::pmr::monotonic_buffer_resource arena(buf, sizeof buf, std::pmr::null_memory_resource());
  std::pmr::vector<int> v(&arena);
  for (int i = 0; i < 10; ++i) v.push_back(i);   // no heap; overflowing buf throws bad_alloc
  int s = 0;
  for (int x : v) s += x;
  return s;
}
```

## Uses-allocator construction and scoped_allocator_adaptor

A container of strings has two levels of allocation: the outer buffer and each string's characters. Uses-allocator construction is the protocol that passes the outer allocator down. A type opts in through `std::uses_allocator<T, Alloc>`, normally by having a nested `allocator_type`, and accepts the allocator either as a trailing constructor argument or after a leading `std::allocator_arg` tag. C++20 exposed the protocol through `std::uses_allocator_construction_args` and `std::make_obj_using_allocator`, and extended it to `std::pair` members.

`polymorphic_allocator::construct` always performs uses-allocator construction, so the elements of a `std::pmr::vector<std::pmr::string>` use the vector's resource with no further work.

```cpp
#include <memory_resource>
#include <string>
#include <vector>

bool nested_uses_arena() {
  std::pmr::monotonic_buffer_resource arena;
  std::pmr::vector<std::pmr::string> v(&arena);
  v.emplace_back("a string long enough to defeat the small buffer");
  return v[0].get_allocator().resource() == &arena;   // true
}
```

For allocators that do not do this themselves, C++11's `std::scoped_allocator_adaptor<Outer, Inner...>` wraps the outer allocator and performs uses-allocator construction of each element with the inner allocator. It predates `std::pmr` and is mostly seen in code that uses custom arena allocators without virtual dispatch.

## allocate_at_least (C++23)

Real allocators round requests up to a size class, so asking for 13 elements might return room for 16. C++23 lets the container learn that. `std::allocator_traits<A>::allocate_at_least(a, n)` returns a `std::allocation_result` holding `ptr` and `count`, with `count >= n`. It calls the allocator's own `allocate_at_least` if it has one, and otherwise returns `{a.allocate(n), n}`. `std::allocator` provides the member.

The obligation runs the other way on deallocation: pass `deallocate` a size between the requested `n` and the returned `count`, normally `count` itself. A `vector` that records the returned count as its capacity can absorb the extra slack before reallocating. Whether a given library uses it inside its containers is an implementation choice, and the standard resources do not offer it.

## What to remember

- Equal allocators can free each other's memory; that one rule decides when buffers may change hands.
- A minimal allocator needs `value_type`, `allocate`, `deallocate`, `==` and a converting constructor; `allocator_traits` supplies the rest.
- Node-based containers rebind the allocator to their node type, and rebound copies must compare equal.
- POCCA, POCMA and POCS decide whether the allocator follows the elements. Move construction always takes the source's allocator.
- Move assignment with unequal, non-propagating allocators moves element by element and may throw, so such containers are not nothrow move assignable.
- Swapping containers with unequal, non-propagating allocators is undefined.
- `polymorphic_allocator` never propagates, and copy construction uses the default resource, not the source's.
- `monotonic_buffer_resource` never frees until release; pool resources reuse blocks by size; `null_memory_resource` makes overflow an error.
- `polymorphic_allocator` performs uses-allocator construction, so nested pmr containers share the outer resource; `scoped_allocator_adaptor` does the same for other allocators.
- `allocate_at_least` (C++23) reports the real size of an allocation through `allocator_traits`.

## Concept Map Outline

- **Allocators and pmr:** An allocator is a handle to a memory source; equal handles can free each other's memory.
  - **Allocator model:** Containers reach allocators only through allocator_traits.
    - **Minimal allocator:** value_type, allocate, deallocate, == and a converting constructor are enough.
    - **Traits defaults:** construct, destroy, pointer, max_size and is_always_equal = is_empty come from traits.
    - **Rebind:** Node containers allocate nodes through rebind_alloc; rebound copies must compare equal.
  - **Propagation traits:** Decide whether the allocator follows the elements on copy, move and swap.
    - **Copy construction:** Uses select_on_container_copy_construction of the source's allocator.
    - **POCMA false, unequal:** Move assignment allocates and moves elements one by one, so it may throw.
    - **POCS false, unequal:** swap is undefined behavior; there is no element-wise fallback.
    - **Move construction:** Always moves the allocator and adopts the buffer; it is noexcept.
  - **polymorphic_allocator:** Stores a memory_resource* and forwards to its virtual interface.
    - **memory_resource:** Public allocate, deallocate, is_equal call private virtual do_ functions.
    - **Never propagates:** POCCA, POCMA and POCS are all false, so a container keeps its resource.
    - **Copies use default:** Copy construction picks get_default_resource(), not the source's resource.
    - **Not nothrow move-assign:** pmr::vector move assignment is noexcept(false) because resources may differ.
  - **Standard resources:** Two global resources and three resource classes ship with the library.
    - **new_delete_resource:** Uses ::operator new; it is the initial default resource.
    - **null_memory_resource:** Throws bad_alloc on every allocation; an upstream that forbids fallback.
    - **monotonic_buffer_resource:** Bump allocation; deallocate is a no-op until release() or destruction.
    - **Pool resources:** Reuse fixed-size blocks; the synchronized version is thread-safe.
  - **Uses-allocator construction:** Passes the container's allocator down to elements that accept one.
    - **Opting in:** uses_allocator, via nested allocator_type, plus a trailing or allocator_arg-led parameter.
    - **pmr does it:** polymorphic_allocator::construct makes nested pmr strings share the outer resource.
    - **scoped_allocator_adaptor:** C++11 adaptor that performs the same protocol for other allocators.
  - **allocate_at_least:** C++23: allocator_traits returns {ptr, count} with count >= n.
    - **Fallback:** Without a member, traits return {allocate(n), n}.
    - **Deallocate size:** Pass a size between the requested n and the returned count.

## Standardese Quiz Questions

### Question 1 [warmup] ([allocator.requirements], [allocator.traits])

In C++23, is this program well-formed?

```cpp
#include <cstddef>
#include <list>
#include <new>

template <class T>
struct Mini {
  using value_type = T;
  Mini() = default;
  template <class U> Mini(const Mini<U>&) noexcept {}
  T* allocate(std::size_t n) { return static_cast<T*>(::operator new(n * sizeof(T))); }
  void deallocate(T* p, std::size_t n) noexcept { ::operator delete(p, n * sizeof(T)); }
};
template <class T, class U>
bool operator==(const Mini<T>&, const Mini<U>&) { return true; }

int main() {
  std::list<int, Mini<int>> l{1, 2, 3};
  return static_cast<int>(l.size()) - 3;
}
```

A. Ill-formed: `Mini` has no `construct` or `destroy` members
B. Ill-formed: `std::list` needs a nested `rebind` template to allocate nodes
C. Ill-formed: `operator!=` is missing
D. Well-formed

**Answer (D):** Well-formed

**Why:** Containers use allocators only through `std::allocator_traits`, which supplies `construct` and `destroy` through `std::construct_at` and `std::destroy_at`, and a default `rebind_alloc` that replaces the first template argument, turning `Mini<int>` into `Mini<Node>`. The converting constructor is what lets the list build that rebound allocator. Since C++20, `a != b` is rewritten to `!(a == b)`, so no separate `operator!=` is needed.

### Question 2 [warmup] ([mem.res.monotonic.buffer.mem])

What does the standard guarantee about `same`?

```cpp
#include <memory_resource>

int main() {
  std::pmr::monotonic_buffer_resource mr;
  void* p = mr.allocate(64);
  mr.deallocate(p, 64);
  void* q = mr.allocate(64);
  bool same = (p == q);
  return same;
}
```

A. `same` is false: `deallocate` does nothing, so the block is not reused before `release()`
B. `same` is true: the freed block is the best fit for the next request
C. It is unspecified
D. Undefined behavior: a monotonic resource does not support `deallocate`

**Answer (A):** `same` is false: `deallocate` does nothing, so the block is not reused before `release()`

**Why:** `monotonic_buffer_resource::do_deallocate` has no effect; memory goes back only when `release()` is called or the resource is destroyed. The next allocation is carved from unused space, so it cannot overlap the first block, which is still allocated as far as the resource is concerned. Calling `deallocate` is valid, it is just a no-op, which is what makes this resource so fast. Reuse of freed blocks is what the pool resources do.

### Question 3 [warmup] ([mem.res.global])

What does this program print?

```cpp
#include <cstdio>
#include <memory_resource>
#include <new>

int main() {
  try {
    void* p = std::pmr::null_memory_resource()->allocate(1);
    std::puts(p ? "allocated" : "null");
  } catch (const std::bad_alloc&) {
    std::puts("bad_alloc");
  }
}
```

A. `null`
B. `allocated`, because the request falls back to the default resource
C. `bad_alloc`
D. Nothing predictable: the behavior is undefined

**Answer (C):** `bad_alloc`

**Why:** Every call to `allocate` on `null_memory_resource()` throws `std::bad_alloc`; it never returns null, because `memory_resource::allocate` reports failure only by exception. There is no fallback, which is the point: as the upstream of a monotonic or pool resource, it turns "ran out of the local buffer" into an error instead of a silent heap allocation.

### Question 4 [tricky] ([mem.poly.allocator.mem], [container.alloc.reqmts])

What does this program print?

```cpp
#include <cstdio>
#include <memory_resource>
#include <vector>

int main() {
  std::pmr::monotonic_buffer_resource arena;
  std::pmr::vector<int> a({1, 2, 3}, &arena);
  std::pmr::vector<int> b = a;
  std::printf("%d %d\n", b.get_allocator().resource() == &arena,
              b.get_allocator().resource() == std::pmr::get_default_resource());
}
```

A. `1 0`
B. `0 1`
C. `1 1`
D. `0 0`

**Answer (B):** `0 1`

**Why:** Copy construction asks `select_on_container_copy_construction()` for the new container's allocator, and `polymorphic_allocator` returns a default-constructed allocator, which uses `get_default_resource()`. So the copy does not follow the source into `arena`. The first answer is what you get with an allocator that copies its state, and it is the usual expectation; `std::pmr` deliberately avoids it so that copies never outlive a scoped resource.

### Question 5 [tricky] ([container.alloc.reqmts], [mem.poly.allocator.class])

What does this program print?

```cpp
#include <cstdio>
#include <memory_resource>
#include <utility>
#include <vector>

int main() {
  std::pmr::monotonic_buffer_resource r1, r2;
  std::pmr::vector<int> a({1, 2, 3}, &r1);
  std::pmr::vector<int> b(&r2);
  const int* old = a.data();
  b = std::move(a);
  std::printf("%d %d %zu\n", b.get_allocator().resource() == &r2,
              b.data() == old, b.size());
}
```

A. `0 1 3`: `b` takes `a`'s allocator and buffer
B. `1 1 3`
C. `1 0 0`
D. `1 0 3`

**Answer (D):** `1 0 3`

**Why:** `polymorphic_allocator` does not propagate on move assignment, and the two allocators compare unequal because their resources differ. `b` keeps its allocator, and since that allocator cannot free memory from `r1`, `b` cannot adopt `a`'s buffer; it allocates from `r2` and moves the elements individually. The first option is what `std::vector<int>` with `std::allocator` does, where move assignment is a pointer steal. The container requirements still guarantee `b` ends up with `a`'s former value.

### Question 6 [tricky] ([mem.poly.allocator.mem], [allocator.uses.construction])

What does this program print?

```cpp
#include <cstdio>
#include <memory_resource>
#include <string>
#include <vector>

int main() {
  std::pmr::monotonic_buffer_resource arena;
  std::pmr::vector<std::pmr::string> v(&arena);
  v.emplace_back("a string long enough to defeat the small buffer");
  std::printf("%d\n", v[0].get_allocator().resource() == &arena);
}
```

A. `0`, because the string was constructed from `const char*` with no allocator
B. `1`
C. `0`, because `polymorphic_allocator` does not propagate
D. It depends on whether the string fits in the small buffer

**Answer (B):** `1`

**Why:** `polymorphic_allocator::construct` performs uses-allocator construction. `std::pmr::string` uses a `polymorphic_allocator<char>`, so the vector's allocator is appended to the constructor arguments and the string's characters come from `arena`. Non-propagation is about copy, move and swap of the container, not about constructing its elements, which is why the third option is wrong. A string's allocator is set at construction regardless of its length.

### Question 7 [standardese] ([vector.overview], [container.alloc.reqmts])

With a conforming C++23 standard library, which of these assertions fails?

```cpp
#include <memory_resource>
#include <type_traits>
#include <vector>

static_assert(std::is_nothrow_move_constructible_v<std::pmr::vector<int>>);  // A
static_assert(std::is_nothrow_move_assignable_v<std::vector<int>>);           // B
static_assert(std::is_nothrow_move_assignable_v<std::pmr::vector<int>>);      // C
```

A. A
B. B
C. C
D. None of them

**Answer (C):** C

**Why:** `vector`'s move assignment is declared `noexcept(propagate_on_container_move_assignment::value || is_always_equal::value)`. For `std::allocator` POCMA is true, so B holds. For `polymorphic_allocator` both are false, because move assignment between unequal resources must allocate and move elements one by one, which can throw; so C fails. Move construction is unconditionally `noexcept`, because it always moves the allocator along with the buffer, so A holds. The failing `static_assert` makes this translation unit ill-formed, which is an easy way to check the answer.

### Question 8 [standardese] ([container.reqmts], [container.alloc.reqmts])

What does the standard say about this program?

```cpp
#include <memory_resource>
#include <vector>

int main() {
  std::pmr::monotonic_buffer_resource r1, r2;
  std::pmr::vector<int> a({1, 2}, &r1);
  std::pmr::vector<int> b({3}, &r2);
  a.swap(b);
}
```

A. Well-defined: the elements are swapped one by one, as move assignment would do
B. Well-defined: the buffers and the resources are exchanged
C. Ill-formed: `polymorphic_allocator` is not swappable
D. Undefined behavior

**Answer (D):** Undefined behavior

**Why:** The container requirements say that when `propagate_on_container_swap` is false, the allocators are not swapped, and the behavior is undefined unless the two allocators compare equal. Here they use different resources, so they are unequal. Unlike move assignment, swap has no element-wise fallback, because it is required to run in constant time without moving individual elements. The second option is what happens when POCS is true.
