Destroy vs Deallocate
In chapter 11 of Accelerated C++, the authors present a Vector class
emulating the behaviour of std::vector using arrays. They use the
allocator class to handle memory management. The role of the uncreate
function is to destroy each element of the array and deallocate the space
allocated for the array:
template <class T> void Vec<T>::uncreate() {
if (data) {
// destroy (in reverse order) the elements that were constructed
iterator it = avail;
while (it != data)
alloc.destroy(--it);
// return all the space that was allocated
alloc.deallocate(data, limit - data);
}
// reset pointers to indicate that the Vec is empty again
data = limit = avail = 0;
}
Obviously we need to deallocate allocated space. But it's unclear to me
why we need to destroy individual elements as well. What would happen if
we only deallocated memory without destroying individual elements?
No comments:
Post a Comment