When we call
delete[] array; // array is a pointer to an array
or
delete[] vector; // vector is a pointer to a vector
Assuming these are array/vector of linked list head pointers: Do these 2 statements call the destructors for every item in them? Or should we loop through them, delete each item and then delete[] the array or vector itself?
Let me be more specific, If the array holds a head pointer with its destructor is called it deletes its next node or that it points to.
Calling
delete[]
on astd::vector
is not correct C++. The vector is destroyed when it goes out of scope or when youdelete
a pointer to it if allocated on the heap withnew
. In both cases, however, destroying the array/vector does not calldelete
on the pointers it contains - you need to iterate through and do this yourself if you need to free that memory.Your second code snippet is incorrect.
delete
anddelete[]
are two different operators.delete
is for delete an instance created bynew
anddelete[]
is for delete an array of elements created bynew[]
.In C++, arrays and vectors does not care about what they store. For both array and vector, you need to delete each item (if they were allocated using
new
) before deleting the array and the vector.If you create the array like this
you need to delete them like this
If you create the vector like this
you need to delete like this
Deleting an array of pointers delete[] array is suitable, but for an vector of pointers i would use a construct like this: