I'm trying to implement a vector, and i have read that the best implementation uses the allocator class(memory header file). I have no idea what is it and the site cplusplus.com didn't help me at all.
-
3[`std::allocator`](http://en.cppreference.com/w/cpp/memory/allocator) – Praetorian Apr 18 '12 at 14:33
-
Related (not a duplicate, since it is a more-specific usage not covered by the present question): [What is a void `std::allocator`? ie: `std::allocator
`](https://stackoverflow.com/questions/67053471/what-is-a-void-stdallocator-ie-stdallocatorvoid). – Gabriel Staples Apr 12 '21 at 06:56
2 Answers
It is an abstraction of memory management.
In C programming, you essentially use the functions malloc()
and free()
to allocate chunks of memory without needing to know how the chunks are allocated. In C++, the functions are operator new()
and operator delete()
.
std::allocator
is a template taking one type parameter, which is the type of objects to be allocated. Instantiations of std::allocator
use operator new()
and operator delete()
internally, but the fact that std::allocator<T>
has information about what T
is means that it knows how to construct and destroy T
objects.
The four basic functions of std::allocator<T>
are:
allocate(size_type n)
Uses
operator new()
to allocate space forn * sizeof (T)
bytes. Note that none of then
T
objects that are allocated are constructed; unlikenew T()
, which both allocates space for oneT
object and calls a no-arg constructor,allocate(size_type n)
only allocates space forn
T
objects. You need to useconstruct()
to explicitly construct each one.deallocate(pointer p, size_type n)
Uses
operator delete()
to free the memory returned by a previous call toallocate()
. Note thatdeallocate()
only releases the space. You must explicitly calldestroy()
on each of then
T
objects or else you may leak memory.construct(pointer p, const T& val)
Calls the
T
copy constructor for theT
object located atp
.destroy(pointer p)
Calls the
T
destructor on theT
object located atp
.

- 38,421
- 18
- 121
- 193
-
+1, Had read some articles and SO answers on `std::allocator` but this is first time I understood it. Thank you :) – Angelus Mortis Jan 08 '16 at 16:20
It is a class which does the memory management of the standard library container classes.
However, If you want to provide your own memory management you can do so, std::allocator
provides the default memory management.

- 202,538
- 53
- 430
- 533
-
Yes, but how is it used in the vector implementation? – Rontogiannis Aristofanis Apr 18 '12 at 14:37
-
@RondogiannisAristophanes: Implementation dependent, as a user of the container, one need not know. – Alok Save Apr 18 '12 at 14:39