If vec.resize(0); vec.shrink_to_fit();
(C++11) as proposed above is not available, you can get something very similar with vector<int>().swap(vec);
. Though putting it into an extra {}
block is preferrable, if this can be done (not always easy, but usually doable).
Note, however, that swapping with a temporary will quite possibly do a (needless) dynamic allocation for the temporary object that you swap and leave a small block allocated until the end of the current scope.
It will also obviously not free the 4-8 bytes of memory that the actual vector
object -- as opposed to the data it holds -- occupies on the stack (only end of scope can do that).
That said, in most cases, the entire endeavour will be kind of futile. If you don't need huge amounts of memory later in the same scope, it doesn't really matter whether you free the vector early or late. Either it already failed much earlier (in that case, the entire problem doesn't arise!), or it will work to the end of the function either way.
On the other hand, if you know that you will need huge amounts of memory later in the same function (say, another vector of similar size) and it is reasonable to expect that this will become a problem, it is hard to predict whether freeing the first really makes a difference (think fragmentation, especially when doing the swap
trick).
You can only expect this to work reliably if the second vector is the same size or smaller than the first one, in every other case it's not guaranteed to work any better.