There are two reasons why the process keeps the memory:
std::vector
will only reallocate memory when it grows, not when it shrinks.
- Freed memory is often retained by the process to be reused.
In C++11, vectors have a shrink_to_fit
member function, which will ask the vector to reduce the amount of allocated memory if possible. There's no guarantee that it will do that, though. In C++03, or if you want to guarantee that the excess memory is freed, you can use the trick of swapping the vector with a newly allocated one:
std::vector<int>(test).swap(test);
or if you want to clear it completely:
std::vector<int>().swap(test);
This trick moves the ownership of the allocated memory to a temporary vector; at the end of the expression, that vector is destroyed, freeing the memory.
Whether or not the memory is released from the process is entirely up to how your library manages the free store. Often, small allocations (up to a few megabytes, perhaps) are handled by a heap - the process requests large blocks of memory from the system, and splits them up into small pieces. The blocks can't be released unless all the small pieces have been freed, and many implementations won't release them even then.
Larger allocations may be requested directly from the system, in which case they will be released once they are freed.
So you may get the effect you expect with code like this:
// A few gigabytes will probably be allocated directly.
// You'll have to reduce this on a 32-bit system, or if there's not enough memory
std::vector<int> test(1000000000)
// Use the "swap trick" to ensure the memory is deallocated.
std::vector<int>().swap(test);
But there is no guarantee that even this will release the memory from the process; the details of memory allocation aren't specified by the standard, and are up to the compiler/library implementation.