Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I deallocate contents of a vector upon its destruction?

Tags:

c++

stl

As far as I know that for both vector declarations as:

//TYPE 1
std::vector<cls> vec;     //cls is user defined datatype(A class)

Memory for vector is allocated on stack and the memory of contents in the vector is allocated on heap.

It is true for the below declaration as well(Correct me if I am wrong):

//TYPE 2
std::vector<cls*> vec;    //cls is user defined datatype(A class)

Now when the vector in Type 1 goes out of scope, memory is deallocated for the objects stored in it.

But what happens in type 2 if I insert elements as below(assuming that I have the proper overloaded constructor) and then the vector goes out of scope:

vec.push_back(new cls(5));

I explicitly tried calling clear but the destructor was not invoked. Will the memory be automatically be deallocated and the destructors be called. If not then how to achieve that.

Also, where is memory allocated for the vector as well as the contents if I declare vector as:

std::vector<cls*> *vec = new std::vector<cls*>;
like image 215
Saksham Avatar asked Jul 29 '13 13:07

Saksham


People also ask

How do you clear the elements of a vector?

vector::clear() clear() function is used to remove all the elements of the vector container, thus making it size 0.

Do you have to deallocate a vector?

No. The std::vector will automatically de-allocate the memory it uses. However, don't do this: std::vector< int *> Ints(2, new int (0));

Does vector erase deallocate memory?

Yes. vector::erase destroys the removed object, which involves calling its destructor.


1 Answers

This is why we have smart pointers.

{
    std::vector<std::unique_ptr<cls>> vec;

    // C++14 will allow std::make_unique
    vec.emplace_back(std::unique_ptr<cls>(new cls(5)));
}

When the vector goes out of scope, the destructors of the unique_ptrs will be called and the memory will be deallocated.

In your case, with the raw pointers, you'd have to delete whatever you created with new manually:

// Something along the lines of this.
for (auto&& elem : vec) {
    delete elem;
}

Also, where is memory allocated for the vector as well as the contents if I declare vector as:

You're allocating the vector with new, so it'll be on the heap.

like image 81
user123 Avatar answered Nov 01 '22 11:11

user123