Say I have:
vector<string>* foo = new vector<string>();
I add a ton of stuff to it, use it, and then I just call:
delete foo;
Did I need to call foo.clear();
first? Or will the delete
call the destructor.
Please no comments regarding the folly of this, I know that at a minimum auto-pointers should be used here. This behavior is in the code base I'm working in and it's outside scope for me to go fix it.
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
}
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,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With