Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does allocator in c++ provide specialization for type void

Tags:

c++

stl

allocator

I notice that the allocator in c++ provides specialization for type void. Is there any special purpose to do this? It doesn't make sense to allocate memory for void type, right?

like image 710
Xiaotian Pei Avatar asked Aug 22 '11 06:08

Xiaotian Pei


People also ask

Which allocator member function do standard containers use to acquire storage for their elements in C++?

The std::allocator class template is the default Allocator used by all standard library containers if no user-specified allocator is provided.

What is allocator in STL?

allocator is the memory allocator for the STL containers. This container can separate the memory allocation and de-allocation from the initialization and destruction of their elements. Therefore, a call of vec. reserve(n) of a vector vec allocates only memory for at least n elements.

Where does the allocators are implemented in C++?

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

This old Standard Librarian column by Matt Austern has a fairly thorough discussion of allocators in general, including this tidbit:

What do we do about void? Sometimes a container has to refer to void pointers, and the rebind mechanism almost gives us what we need, but not quite. It doesn't work, because we would need to write something like malloc_allocator::pointer, and we've defined malloc_allocator in such a way that instantiating it for void would be illegal. It uses sizeof(T), and it refers to T&; neither is legal when T is void. The solution is as simple as the problem: specialize malloc_allocator for void, leaving out everything except the bare minimum that we need for referring to void pointers.

malloc_allocator is the sample implementation that Austern uses in his example, but it holds true for the general case.

like image 162
Gnawme Avatar answered Nov 15 '22 16:11

Gnawme