When you use delete
, the destructor of the pointed-to object is called before de-allocation (do this, when you have created an object using new
).
Similarly, the destructors of all created objects are called when you use the array version delete[]
(do this, when you have allocated an array of objects using new[]
).
The destructor of a std::vector<T>
automatically calls the destructors of the contained objects.
So, as Joachim Pileborg has pointed out in his answer, you need to take care of deleting the vector's objects manually, only when you have raw pointers in there that point to dynamically allocated objects (e.g., objects allocated by new
) and you are responsible for their deletion (i.e., you own them). Raw pointers don't have destructors that would destroy the pointed-to objects, so you would have to iterate the vector to delete the objects manually in this case.
Otherwise the vector can simply be destroyed (or array-deleted, in this case).
As a rule of thumb:
- You need to
delete
memory you have allocated using new
.
- You need to
delete[]
memory you have allocated using new[]
.
- You can pass this obligation to smart pointers, i.e., objects that implement an ownership policy that will take care of the proper deallocation.
- You should avoid dynamic memory allocation where ever possible and prefer schemes like RAII for memory management.
For reference: