"Right" way to deallocate an std::vector object
Solution 1:
The simplest and most reliable way to deallocate a vector is to declare it on the stack and simply do nothing.
void Foo() {
std::vector<int> v;
...
}
C++ guarantees that the destructor of v
will be called when the method executes. The destructor of std::vector
will ensure any memory it allocated is freed. As long as the T
type of the vector<T>
has proper C++ deallocation semantics all will be well.
Solution 2:
The simplest way to deallocate all the storage in a vector, without destroying the vector object itself, is
vec = std::vector<int>();
Your second variant will have the same effect, but it jumps through more hoops on the way. The "copy and swap" trick deallocates any extra capacity in the vector, and can be useful if it contains some data you want to keep. If there's no data, then there's no need for copying or swapping.
Solution 3:
std::vector<int> vi;
/*push lots of stuff into the vector*/
// clean it up in C++03
// no need to clear() first
std::vector<int>().swap(vi);
// clean it up in C++0x
// not a one liner, but much more idiomatic
vi.clear();
vi.shrink_to_fit();
Solution 4:
I agree with Mike Seymour try this then you will notice that the last is working fine
const int big_size = 10000;
vector<double> v( big_size );
cout << "Before clearing, the capacity of the vector is "
<< v.capacity() << " and its size is " << v.size();
v.clear();
cout << "\nAfter clearing, the capacity of the vector is "
<< v.capacity() << " and its size is " << v.size();
vector<double>().swap( v );
cout << "\nAfter swapping, the capacity of the vector is "
<< v.capacity() << " and its size is " << v.size();
vector<double> v1( big_size );
v1 = vector<double>();
cout << "\n After vector<double>();, the capacity of the vector is "
<< v1.capacity() << " and its size is " << v1.size();