As we’ve introduced in C++ Dynamic Memory, C++ support new/delete
pair to manage the memory in free store, which automatically invoke the contructor/destructor when allocate/deallocate the space, which can be a resource waste when allocate dynamic array. To avoid the invocation of constructor, use allocator
to allocate the memory manually:
std::allocator<std::string> alloc;
auto const p = alloc.allocate(n);
At first we need to construct an allocator to particular type, which can only used to allocate the space of that type, then we invoke the allocate
method of that allocator, here we allocated n
uninitialized std::string
.
The memory allocated by allocator
is unconstructed, method construct
can be used to construct element in given address:
auto q = p;
alloc.construct(q++);10, 'c');
alloc.construct(q++, "hi"); alloc.construct(q++,
Once we’re done with some objects (but not the entire allocated space), we use the destroy
method, which inovke the destructor of object, to destroy them:
while (q != p) alloc.destroy(--q);
We can reuse those destroyed space for new elements.
Finally if the allocated space can be free, we use deallocate
method:
alloc.deallocate(p, n);
Three conditions must meet to use deallocate
:
deallocate
must be returned by allocate
previouslyn
must be exactly the size when we allocate