4

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.

Rontogiannis Aristofanis
  • 8,883
  • 8
  • 41
  • 58
  • 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 Answers2

9

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:

  1. allocate(size_type n)

    Uses operator new() to allocate space for n * sizeof (T) bytes. Note that none of the n T objects that are allocated are constructed; unlike new T(), which both allocates space for one T object and calls a no-arg constructor, allocate(size_type n) only allocates space for n T objects. You need to use construct() to explicitly construct each one.

  2. deallocate(pointer p, size_type n)

    Uses operator delete() to free the memory returned by a previous call to allocate(). Note that deallocate() only releases the space. You must explicitly call destroy() on each of the n T objects or else you may leak memory.

  3. construct(pointer p, const T& val)

    Calls the T copy constructor for the T object located at p.

  4. destroy(pointer p)

    Calls the T destructor on the T object located at p.

Daniel Trebbien
  • 38,421
  • 18
  • 121
  • 193
0

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.

Alok Save
  • 202,538
  • 53
  • 430
  • 533