Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 872
Jacob Avatar asked Jun 16 '10 15:06

Jacob


People also ask

How do you clear a vector in C++?

C++ Vector Library - clear() Function The C++ function std::vector::clear() destroys the vector by removing all elements from the vector and sets size of vector to zero.

How do I completely clear a vector content?

All the elements of the vector are removed using clear() function. erase() function, on the other hand, is used to remove specific elements from the container or a range of elements from the container, thus reducing its size by the number of elements removed.

Do you need to delete a vector?

The vector (like all standard containers) owns the objects inside it. So it is responsible for destroying them. Note: If you vector contains pointers then it owns the pointers (not what the pointers point at). So these need to be deleted.


1 Answers

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.

like image 76
JaredPar Avatar answered Oct 06 '22 08:10

JaredPar