The first solution is:
std::vector<int> *vec = new std::vector<int>;
assert(vec != NULL);
// ...
delete vec;
An alternative is:
std::vector<int> v;
//...
vec.clear();
vec.swap(std::vector<int>(vec));
The second solution’s a bit of a trick — what’s the "right" way to do it?
Update:
I’m aware that the destructor will be called once it’s off the stack, I was curious about other methods.
The simplest and most reliable way to deallocate a vector is to declare it on the stack and simply do nothing.
C++ guarantees that the destructor of
vwill be called when the method executes. The destructor ofstd::vectorwill ensure any memory it allocated is freed. As long as theTtype of thevector<T>has proper C++ deallocation semantics all will be well.