0

The first line from cpp reference says 'The std::allocator class template is the default Allocator used by all standard library containers if no user-specified allocator is provided...' From the given example I can see that it's used to do some memory allocation based on type:

std::allocator<int> a1;   // default allocator for ints
int* a = a1.allocate(1);  // space for one int
a1.construct(a, 7);       // construct the int
std::cout << a[0] << '\n';
a1.deallocate(a, 1);      // deallocate space for one int

However I can still do something similar with:

auto a = std::make_unique<int>(7); // single int usage

and a some std container if I want multiple ints with contiguous access.

So when and why do I need std::allocator?

Quentin
  • 62,093
  • 7
  • 131
  • 191
ssh
  • 369
  • 7
  • 7

1 Answers1

1

In short, it is useful to be able to control how you allocate dynamic memory. The obvious answer is new and delete, but sometimes people use other types of memory allocation, such as allocating a big amount of memory upfront and chunking it or just using the stack as memory.

The allocator model abstracts over this, by providing functions that give the containers memory to play around with. We don't really care where the memory we use comes from, just that there is enough of it when we need it.

std::allocator in itself uses new and delete, and is the template default for all standard library containers. It is the default choice when you do not want any other allocation model. So to answer your question, you use std::allocator all the time, whenever you don't provide another allocator to your containers.

user975989
  • 2,578
  • 1
  • 20
  • 38