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();
Yes. vector::erase destroys the removed object, which involves calling its destructor.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With