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.