"Right" way to deallocate an std::vector object

c++, memory-management, stl, vector

Solution

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.

Problem

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.

Original source