What is a allocater?

What is it and what is it used for?

I'm a beginner so try to have some easy to understand info while being informative at the same time, i've google'd it but can't really understand it.
An allocator is an object that deals with memory model matters. It describes how to allocate/release storage and how to point to/reference an object in that storage.
is a memory model like a template for how memory is stored?
Allocator is a class that can do four main things:
1) obtain storage
2) construct objects in allocated storage
3) destruct objects
4) release storage

For example:

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

int main()
{
    std::allocator<std::string> a;

    std::string* data = a.allocate(2); // allocate storage for 2 strings
    a.construct(data, "Hello"); // constructs a string
    a.construct(data+1, "world"); // constructs another string

    std::cout << data[0] << ", " << data[1] << '\n';

    a.destroy(data + 1); // destructs a string
    a.destroy(data); // destructs another string
    a.deallocate(data, 2); // frees storage
}


Whenever you're using a vector, a string, or another C++ container, or a shared pointer, or anything else that needs to allocate memory at runtime, you are using std::allocator and you're provided with an opportunity to substitute your own.

This std::allocator is not very interesting, it just calls new and delete, but user-defined allocators can be a whole lot more interesting - they can obtain storage from a memory pool (which can be very fast for fixed-size objects), from shared memory (so that many programs can access the same vector), from stack (again, fast), from thread-local storage, from other sources.

At my work, for example, there are special memory areas that are bound to user id - if I create a vector with an allocator that uses that area, the user can log out, log back in, restart my program, and the vector is already there.
Last edited on
Topic archived. No new replies allowed.