Post

std::allocator

std::allocator

std::allocator


Prerequisites


1. What is an Allocator

An allocator is a mechanism that handles memory allocation and deallocation

for objects used in containers like:

  • std::vector
  • std::list
  • std::map

Containers do not allocate memory directly

Instead:

1
Container → Allocator → Memory

When It Matters:

  • high-frequency allocation
  • real-time systems
  • game engines
  • memory-constrained environments

Basic Usage

1
2
3
4
#include <memory>

std::allocator<int> alloc;
int* p = alloc.allocate(5);  // allocate space for 5 ints

Only allocates memory (no construction)

Construct Object
1
std::construct_at(p, 10);
Destroy Object
1
std::destroy_at(p);
Deallocate Memory
1
alloc.deallocate(p, 5);

Full Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <memory>

int main()
{
    std::allocator<int> alloc;

    int* p = alloc.allocate(1);
    std::construct_at(p, 42);       // new(p) int(42);

    std::cout << *p << "\n";

    std::destroy_at(p);
    alloc.deallocate(p, 1);
}

2. Why Allocator Exists

2-1. Separation of Concerns

  • Container → data structure logic
  • Allocator → memory management

2-2. Custom Memory Strategies

You can replace default allocator with:

  • memory pool
  • arena allocator
  • stack allocator

2-3. Performance Optimization

👉 Avoid frequent new/delete

Example

1
std::vector<int> v;

Internally:

1
std::vector<int, std::allocator<int>>

Custom Allocator Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
template<typename T>
struct MyAllocator
{
    using value_type = T;

    T* allocate(size_t n)
    {
        return static_cast<T*>(::operator new(n * sizeof(T)));
    }

    void deallocate(T* p, size_t)
    {
        ::operator delete(p);
    }
};
1
std::vector<int, MyAllocator<int>> v;

3. Advanced Concepts

Rebinding (Old concept)

Used to allocate different types. Mostly replaced by allocator_traits

1
std::allocator<int>
1
Alloc::rebind<U>::other
1
2
std::allocator<int> alloc; // std::allocator<double>: want to be exchanged
typename std::allocator<int>::rebind<double>::other new_alloc;

Allocator Traits

1
std::allocator_traits<Alloc>
1
2
using Alloc = std::allocator<int>;
using NewAlloc = std::allocator_traits<Alloc>::rebind_alloc<double>;

Standard way to interact with allocators

construct/destroy

❗ Deprecated
1
2
alloc.construct(...)
alloc.destroy(...)
✔️ Use Instead
1
2
std::construct_at(ptr, args...);
std::destroy_at(ptr);
FeatureAllocatornew/delete
AbstractionHighLow
FlexibilityHighLow
CustomizationYesNo
Used in STLYesNo

4. Advanced Concepts

❌ Mixing new/delete with allocator

1
2
int* p = new int;
alloc.deallocate(p, 1);  // ❌ wrong
This post is licensed under CC BY 4.0 by the author.