It is well known that vector::swap can be used to effectively free
the allocated memory. ie,
vector<int> v;
vector<int>().swap(v);
Someone suggested another way using a placement-new.
#include <vector>
using std::vector;
int main()
{
vector<int> v(10);
v.~vector<int>();
new(&v) vector<int>();
}
Is this code portable?
Yes and no. Both of the above code sequences will leave v with the
capacity of a default constructed vector. The standard does not
guarantee that the capacity of a default constructed vector is 0. That
being said, I'm not aware of any implementation which does not have a 0
capacity on default construction.
Assuming for the moment that the vector default constructor does acquire
some resource, either in terms of its capacity, or in the default
construction of std::allocator (again, I know of no implementation which
actually does this), then the swap idiom is safer than the
destruct-construct sequence. With the swap idiom if the default vector
constructor throws an exception, then v is left unmodified. With the
destruct-construct sequence if the default vector constructor throws an
exception, v is left in a destructed state. This is likely to cause a
crash later when v is destructed again (likely a double delete of heap
memory).
-Howard