Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Deleting a Dynamically Allocated Vector Clear It's Contents

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.

like image 568
Jonathan Mee Avatar asked Jun 11 '15 15:06

Jonathan Mee


2 Answers

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)

like image 151
Lightness Races in Orbit Avatar answered Sep 28 '22 08:09

Lightness Races in Orbit


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,

like image 45
Vlad from Moscow Avatar answered Sep 28 '22 09:09

Vlad from Moscow