Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are allocators and when is their use necessary? [closed]

Tags:

c++

stl

allocator

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.

like image 438
P0W Avatar asked Jul 25 '13 02:07

P0W


People also ask

What is the use of allocator?

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.

What is use of allocator in C++?

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?

Where are allocators implemented? Explanation: Allocators are implemented in C++ standard library but it is used for C++ template library.

What is a stack allocator?

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.


1 Answers

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.

like image 168
Jerry Coffin Avatar answered Nov 15 '22 17:11

Jerry Coffin