free
MemberThe free
member must destroy
the elements and then deallocate the space this StrVec
allocated. The for
loop calls the allocator
member destroy
in reverse order, starting with the last constructed element and finishing with the first:
void StrVec::free()
{
// may not pass deallocate a 0 pointer; if elements is 0, there's no work to do
if (elements) {
// destroy the old elements in reverse order
for (auto p = first_free; p != elements; /* empty */)
alloc.destroy(--p);
alloc.deallocate(elements, cap - elements);
}
}
The destroy
function runs the string
destructor. The string
destructor frees whatever storage was allocated by the string
s themselves.
Once the elements have been destroyed, we free the space that this StrVec
allocated by calling deallocate
. The pointer we pass to deallocate
must be one that was previously generated by a call to allocate
. Therefore, we first check that elements
is not null before calling deallocate
.