If you are worried about freeing the memory allocated (and hence blocked for use elsewhere) in a (large) vector
, you should
make sure the scope/lifetime of the respective vector is limited to the region/time of its imminent use, so that its destruction automatically frees the memory.
failing that (for whatever reason), you may
vec.clear(); // reduces the size to 0, but not the capacity
vec.shrink_to_fit(); // suggests to reduce the capacity to size
assert(vec.capacity()==0);
Note that vector::clear()
de-allocates no memory in vector
(only memory, if any, dynamically allocated by the vector elements). vector::shrink_to_fit()
suggests the reduction of the memory footprint of vector
to its actual size, but the implementation can chose to ignore that request.
Finally, an alternative to clear()
followed by shrink_to_fit()
is the swap idiom (which also works prior to C++11):
vector<Tp>().swap(vec);
assert(vec.capacity()==0);
What happens here is that a new empty vector (of the same type) is constructed and then immediately swapped with vec
, so that vec
becomes empty (with zero size and capacity). Finally, because the new vector is a temporary (un-named) object, it is destructed, whereby de-allocating the memory originally kept with vec
.