Does Deleting a Dynamically Allocated Vector Clear It's Contents

1.9k views Asked by At

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.

2

There are 2 answers

0
Lightness Races in Orbit On BEST ANSWER

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)

0
Vlad from Moscow On

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,