When you use C++ STL, it takes care of freeing up memory after a variable goes out of scope. But let’s say you have some code that needs the memory to be freed up immediately. This can happen under many circumstances when you are working under constrained resources. One of the more popular STL containers is ‘vector’. Let’s say you have declared a bunch of those in your code and you want to free them up manually. You may think that using clear() on that vector might take care of the situation, but it doesn’t. You can call clear(), and it will destroy all the objects, but it will not free up the memory. So how do we do it?
How do I free up the memory?
A very simple way to do it would be to create an empty dummy vector and swap out the contents. Look at the following the following code:
vector<MyClass> myVector; vector<MyClass>().swap(myVector);
It creates a new vector of ‘MyClass’ objects (which will be empty) and swaps it with myVector. To understand it further, let’s dig a little deeper. You can also write it as:
Here, vector<MyClass>(myVector) creates a new vector with its contents copied from the now empty myVector. The new vector is an anonymous temporary, so let’s pretend it’s name is newVector. Hence, “newVector.swap(myVector)” swaps the new vector with myVector.
Why is it like that?
The reason for this is that by default, std::vector<t>::clear often doesn’t actually reduce the storage used by a vector, it merely destroys all the objects contained there. This way, the vector has room to store more objects without reallocation in the future. Sometimes, however, you want to trim the capacity in the vector. Swapping with a newly created vector (which lives until the end of it’s line, and is therefore destroyed there) frees all the memory allocated by the vector.
C++ exposes memory management here so that you have the chance to customize things for your needs. By default, C++ tries to be as fast as it can. So if you don’t follow this code, you’re going to get faster code. In cases where you have a very large vector and you remove many of its elements, then you can use this method to free up resources to the OS. This will of course be at the expense of speed. Usually you don’t want to do that. You don’t want to fix what’s not broken!