Allocator (C++)

The standard library provides several data structures, such as list and set, commonly referred to as containers.

Allocators were invented by Alexander Stepanov as part of the Standard Template Library (STL).

As a result, the level of customization provided by allocators is more limited than was originally envisioned by Stepanov.

In particular, Stepanov was requested to make the library containers independent of the underlying memory model,[2] which led to the creation of allocators.

In adapting STL to be included in the C++ Standard Library, Stepanov worked closely with several members of the standards committee, including Andrew Koenig and Bjarne Stroustrup, who observed that custom allocators could potentially be used to implement persistent storage STL containers, which Stepanov at the time considered an "important and interesting insight".

Stepanov later described allocators as follows: "A nice feature of STL is that the only place that mentions the machine-related types (...) is encapsulated within roughly 16 lines of code.

"[2] While Stepanov had originally intended allocators to completely encapsulate the memory model, the standards committee realized that this approach would lead to unacceptable efficiency degradations.

[4] Stepanov later commented that, while allocators "are not such a bad [idea] in theory (...) [u]nfortunately they cannot work in practice".

[7] The 2011 revision of the C++ Standard removed the weasel words requiring that allocators of a given type always compare equal and use normal pointers.

The semantics of the functions should be equivalent to the following:[11] The above code uses the placement new syntax, and calls the destructor directly.

Utilizing a specialized custom allocator may substantially improve the performance or memory usage, or both, of the program.

This approach may work well with containers that mostly allocate large chunks of memory, like vector and deque.

[4][17] Other common problems with a malloc-based allocator include poor locality of reference,[4] and excessive memory fragmentation.

Although the C++98 Standard did encourage library implementors to support stateful allocators,[12] Meyers calls the relevant paragraph "a lovely sentiment" that "offers you next to nothing", characterizing the restriction as "draconian".

A function expecting an std::vector argument will therefore only accept a vector instantiated with the default allocator.