Tommy
Tommy

Reputation: 13662

C++ 2D vector clear works as intended?

I want to make sure that the following works as I intend without memory leaks:

vector<vector <float> > X;
for (int i = 0; i < some_size; i++)
{
     vector<float> column;
     X.push_back(column);
}
// ... use 2D array somehow
X.clear(); 
/* CALLS DESTRUCTOR OF EACH ELEMENT, BUT SINCE EACH ELEMENT
IS A VECTOR, CLEAR IS RECURSIVELY CALLED ON EACH OF THOSE*/

That is, is clear() recursively applied to vectors of vectors due to clear being part of a vector's destructor?

I know X is cleared fully when it goes out of scope but that is not the point of the question here.

Upvotes: 4

Views: 4997

Answers (2)

nickie
nickie

Reputation: 5808

Adding to Zac Howland's answer, as the documentation for vector<T>::clear suggests,

A reallocation is not guaranteed to happen, and the vector capacity is not guaranteed to change due to calling this function. A typical alternative that forces a reallocation is to use swap:

vector<T>().swap(x);   // clear x reallocating

This will swap the contents of a temporary empty vector with those of x. Then the destructor will be called for the temporary (previously empty) vector, which will in turn call the destructors for all of its vector elements, and finally all space will be deallocated.

Upvotes: 3

Zac Howland
Zac Howland

Reputation: 15872

Yes and no. It will call the destructor for each element in the top vector, and the destructor for each vector will clear it's own memory (so it isn't calling clear necessarily for each of the inner vectors).

clear is not guaranteed to free up the memory used by the top level vector, however.

Upvotes: 2

Related Questions