Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is std::vector memory freed upon a clear?

People also ask

What happens when you clear a vector?

clear() removes all the elements from a vector container, thus making its size 0. All the elements of the vector are removed using clear() function.

Does vector automatically deallocate memory?

std::vector will not automatically de-allocate the memory, so your program will leak.

Does std::vector clear call Delete?

So what your question should be: "Does std::vector<T*>::clear() call delete on its elements?" and here the answer is: No, it does not call delete . You have to do it manually like shown in your example code, or you can (and probably should) use objects like std::string or smart pointers instead of raw pointers.


The memory remains attached to the vector. That isn't just likely either. It's required. In particular, if you were to add elements to the vector again after calling clear(), the vector must not reallocate until you add more elements than the 1000 is it was previously sized to.

If you want to free the memory, the usual is to swap with an empty vector. C++11 also adds a shrink_to_fit member function that's intended to provide roughly the same capability more directly, but it's non-binding (in other words, it's likely to release extra memory, but still not truly required to do so).


The vector's memory is not guaranteed to be cleared. You cannot safely access the elements after a clear. To make sure the memory is deallocated Scott Meyers advised to do this:

vector<myStruct>().swap( vecs );

Cplusplus.com has the following to say on this:

Removes all elements from the vector, calling their respective destructors, leaving the container with a size of 0.

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


The destructor is called on the objects, but the memory remains allocated.


No, memory are not freed.

In C++11, you can use the shrink_to_fit method for force the vector to free memory.

http://www.cplusplus.com/reference/vector/vector/