While reading books on C++ and the standard library, I see frequent references to allocators.
For example, Nicolai Josuttis's The C++ Standard Library discusses them in detail in the last chapter, and both items 10 ("be aware of allocators' conventions & restrictions") and 11 ("understand the legitimate uses of custom allocators") in Scott Meyers's Effective STL are about their use.
My question is, how do allocators represent a special memory model? Is the default STL memory management not enough? When should allocators be used instead?
If possible, please explain with a simple memory model example.
Allocators are objects responsible for encapsulating memory management. std::allocator is used when you want to separate allocation and do construction in two steps. It is also used when separate destruction and deallocation is done in two steps.
Allocators are used by the C++ Standard Library to handle the allocation and deallocation of elements stored in containers. All C++ Standard Library containers except std::array have a template parameter of type allocator<Type> , where Type represents the type of the container element.
Where are allocators implemented? Explanation: Allocators are implemented in C++ standard library but it is used for C++ template library.
Note: A stack-like allocator means that the allocator acts like a data structure following the last-in, first-out (LIFO) principle. This has nothing to do with the stack or the stack frame. The stack allocator is the natural evolution from the arena allocator.
An allocator abstracts allocating raw memory, and constructing/destroying objects in that memory.
In most cases, the default Allocator is perfectly fine. In some cases, however, you can increase efficiency by replacing it with something else. The classic example is when you need/want to allocate a large number of very small objects. Consider, for example, a vector of strings that might each be only a dozen bytes or so. The normal allocator uses operator new
, which might impose pretty high overhead for such small objects. Creating a custom allocator that allocates a larger chunk of memory, then sub-divides it as needed can save quite a bit of both memory and time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With