Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ delete vector, objects, free memory

I am totally confused with regards to deleting things in C++. If I declare an array of objects and if I use the clear() member function. Can I be sure that the memory was released?

For example :

tempObject obj1; tempObject obj2; vector<tempObject> tempVector;  tempVector.pushback(obj1); tempVector.pushback(obj2); 

Can I safely call clear to free up all the memory? Or do I need to iterate through to delete one by one?

tempVector.clear(); 

If this scenario is changed to a pointer of objects, will the answer be the same as above?

vector<tempObject> *tempVector; //push objects.... tempVector->clear(); 
like image 515
mister Avatar asked May 05 '12 18:05

mister


People also ask

Does vector erase free memory?

Yes. vector::erase destroys the removed object, which involves calling its destructor.

Does delete [] work on vectors?

Yes. For each time a new[] expression is executed, there must be exactly one delete[] . If there is no delete[] , then there is a leak.

How do you destruct a vector?

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.


1 Answers

You can call clear, and that will destroy all the objects, but that will not free the memory. Looping through the individual elements will not help either (what action would you even propose to take on the objects?) What you can do is this:

vector<tempObject>().swap(tempVector); 

That will create an empty vector with no memory allocated and swap it with tempVector, effectively deallocating the memory.

C++11 also has the function shrink_to_fit, which you could call after the call to clear(), and it would theoretically shrink the capacity to fit the size (which is now 0). This is however, a non-binding request, and your implementation is free to ignore it.

like image 150
Benjamin Lindley Avatar answered Oct 12 '22 12:10

Benjamin Lindley