The library class allocator is used to allocate unconstructed memory. It provides us with the means to separate the allocation of memory from the construction of objects in that memory.
From: http://en.cppreference.com/w/cpp/concept/Allocator
“Encapsulates strategies for access/addressing, allocation/deallocation and construction/destruction of objects.”
The class allocator is defined in the header memory. Why does it exist?
The use of new is constrained in that it combines allocating memory with constructing an object, or objects, in that memory.
As we stated earlier, an allocator allows these two operations to be separated.Instances of the class allocator can be use to provide type-aware allocation of raw, unconstructed, memory.
We defined an allocator object for objects of type T as follows:
allocator<T> a;
The operations for allocation, deallocation, creation and destruction are paired, and we will summarise them on the next slide. We will put them in the order they typically need to be used in.
Where is the advantage? You only destroy what you construct.
The arguments on the constructor are, as of C++11, allowed to match any constructor for the relevant class.
allocator<string> alloc;
auto const p = alloc.allocate(5);
// q will be used to point to one past the last constructed.
auto q=p;
alloc.construct(q++); // 3 Constructors
alloc.construct(q++, 10, 'c');
alloc.construct(q++, "hi");
auto r=p;
do // Displaying
cout << *r << endl;
while (++r != q);
while (q != p)
alloc.destroy(--q); // Destroying
alloc.deallocate(p, 5); // Deallocating
The textbook goes on to talk about the use of some algorithms used to construct objects in uninitialized memory.
uninitialized_copy(b, e, b2)
uninitialized_copy_n(b, n, b2)
uninitialized_fill(b, e, t)
uninitialized_fill_n(b, n, t)
These make use of iterators to specify the source to be used to populate the uninitialized memory.