Does Deleting a Dynamically Allocated Vector Clear It's Contents
Yes, the vector
's destructor will be called, and this will clear its contents.
delete
calls the destructor before de-allocating memory, and vector's destructor implicitly calls .clear()
(as you know from letting an automatic-storage duration vector
fall out of scope).
This is quite easy to test, with a vector<T>
where T
writes to std::cout
on destruction (though watch out for copies inside of the vector
):
#include <vector>
#include <iostream>
struct T
{
T() { std::cout << "!\n"; }
T(const T&) { std::cout << "*\n"; }
~T() { std::cout << "~\n"; }
};
int main()
{
std::vector<T>* ptr = new std::vector<T>();
ptr->emplace_back();
ptr->emplace_back();
ptr->emplace_back();
delete(ptr); // expecting as many "~" as "!" and "*" combined
}
(live demo)
According to the requirements of containers (the C++ Standard, Table 96 — Container requirements)
(&a)->~X() - the destructor is applied to every element of a; all the memory is deallocated.
where X denotes a container class containing objects of type T, a and b denote values of type X,