Is std::vector memory freed upon a clear?

The memory remains attached to the vector. If you want to free it, 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.