I've just read about std::allocator
. In my opinion, it is more complicated to use it instead of using new
and delete
.
With allocator
we must explicitly allocate heap memory, construct it, destroy it, and then finally deallocate the memory. So why was it created?
In which cases can it be used and when should it be used instead of new and delete?
The reason for this STL member is to give the developer more control over memory. What I mean by this is, for instance, the new operator is not really just one operation per se. At its most basic, it performs a reservation of memory AND then fills that space with the object.
Although I cannot on top of my head come up with a specific, real-world case scenario, you should use
std::allocator
and such when, perhaps, the destruction of a given object might impact other objects in memory.Let's say, for the sake of argument, you created some kind of vector which each element is double-linked to some other object in memory and you want, at the time of deletion of said vector, the objects linked to remove the reference back to it.