Allocators
An allocator is an object that containers ask for raw memory. std::allocator<T> calls operator new. A custom allocator can serve a pool, an arena, or a tracking heap. C++17 std::pmr is the usual way to swap allocators without rewriting container types.
Detailed Explanation
std::vector<T> does not call new T for each insert. It asks its allocator for n * sizeof(T) bytes, then placement-news the elements. The allocator is a template argument: vector<T, Alloc>. The default Alloc is std::allocator<T>.
Why you would change it:
- An arena that frees everything at once at the end of a request.
- A monotonic buffer on the stack for a short-lived
vector. - A debug allocator that fills freed memory and records stacks.
- A NUMA or GPU-adjacent pool.
The C++98 allocator model required every container type to mention the allocator (vector<T, MyAlloc> is a different type from vector<T>). That split APIs. C++17 polymorphic memory resources (<memory_resource>) put the choice in a runtime pointer: std::pmr::vector<T> is always the same type and holds a memory_resource*. std::pmr::monotonic_buffer_resource and unsynchronized_pool_resource are the stock resources.
allocate_at_least (C++23) and allocate / deallocate pairs must match. An allocator that hands out memory from malloc must free it, not delete[]. Alignment is part of the contract (allocate is aligned for T; over-aligned T needs an allocator that honours alignof(T)).
You rarely write a full C++98 allocator. You write a memory_resource and use pmr::vector. If you must write the old kind, implement allocate, deallocate, ==, and the rebind protocol; std::allocator_traits fills in the rest.
Allocators do not replace RAII. They replace where the bytes come from. Elements still have destructors. A pool that forgets to destroy string elements leaks the strings' own heap buffers.
new / delete still exist for single objects. Allocators shine when a container allocates many times. Do not introduce pmr until a profile shows allocation is the cost.
Code Examples
#include <array>
#include <iostream>
#include <memory_resource>
#include <vector>
int main() {
std::array<std::byte, 1024> buf{};
std::pmr::monotonic_buffer_resource arena{buf.data(), buf.size()};
std::pmr::vector<int> v{&arena};
v.push_back(1);
v.push_back(2);
std::cout << v.size() << '\n'; // prints: 2
} // arena memory is the stack buf#include <memory>
#include <vector>
int main() {
std::vector<int, std::allocator<int>> v{1, 2, 3}; // the default
(void)v[0];
}Common Gotchas
Using memory after the resource dies
a `pmr::vector` whose resource is a local `monotonic_buffer_resource` must die first. Declare the resource before the vector.
Monotonic resources do not free individual allocations
`clear()` on the vector runs destructors but the arena does not reuse bytes until the resource is released.
Thread-safe versus not
`unsynchronized_pool_resource` is single-threaded. Use `synchronized_pool_resource` or a mutex if you share it.