C++: Empty a vector for real

clear() is the method used to empty a STL vector in C++. However, it merely sets the size of the vector to zero. In almost all STL implementations, the vector is still consuming the same amount of memory it was before the call to clear(). This can be seen by calling the capacity() method, which returns the actual number of items which the vector can hold without needing or reallocating any new memory.

#include <iostream>
#include <vector>
int main()
{
    vector< int > v( 1000000 );
    v.clear();
    std::cout << v.capacity() << std::endl; // 1000000
    return 0;
}

But, there will be situations where memory is tight and you would like to actually clear a vector of all its memory. This can be achieved using the shrink_to_fit() method, which was introduced in C++11:

v.clear();
v.shrink_to_fit(); // Capacity of v is now 0

If you are using an old C++ compiler or STL implementation that does not support shrink_to_fit(), there is another trick to empty a vector: swap its contents with a vector that is actually empty:

vector< int >().swap( v ); // Capacity of v is now 0

Our original vector now points to the (empty) space of the new vector. The new vector now points to the capacity of the old vector. But, the lifetime of the new vector is the scope of this statement. As soon as that scope ends, the new vector is deleted, thus freeing the memory occupied by the old vector.

Tried with: Visual C++ 2010

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.