C++ vector dynamic memory deallocation/delete
Solution 1
You can write a generic function to handle both deallocation and erasure of the vector's elements
template<typename T>
void destroy_vector(std::vector<T*> &v)
{
while(!v.empty()) {
delete v.back();
v.pop_back();
}
}
Some remarks
- Always check with
empty
for empty container - Store your
vector<T*>*
in a smart pointer to avoid memory leaks
Solution 2
When you erase an element from vector, elements after that are moved by one place. When you erase the element in index 0, the element in index 1 will be moved to index 0 and will not be erased in the next iteration.
Take the erase from the loop. Elements will be erased in the vectors destructor anyway.
Wade G
Updated on June 27, 2022Comments
-
Wade G almost 2 years
When I try and delete dynamic memory elements of a dynamic vector of objects, I have to iterate over the entire size of the vector more than once to ensure complete deallocation.
class CV{ public: float x; float y; CV(); CV(float, float); ~CV(); }; int main(){ vector<CV*>* cars; cars = new vector<CV*>; //create objects with new, push into vetor for(int j=0;j<4;j++){ cars->push_back( new CV(10.0+j, 11.99+j) ); } while( cars->size() > 0 ){ for(int i=0;i<cars->size();i++){ delete (*cars)[i]; cars->erase( cars->begin()+i); } cout << "size:"<< cars->size() << endl; } delete cars; return 0; }
This will output:
size:2 size:1 size:0
The vector seems to iterate over every second element when I try to delete, as I require the extra while loop to ensure total deallocation.
I seem to be missing something about the internal workings of vector, I've tried reading the vector c++ reference and I understand that vectors store elements in a contiguous location and that they allocate extra storage for possible growth, but I fail to understand the behaviour of this code.
-
Wade G about 10 yearsOk, I understand the elements have to shift when a specific element is erased or removed. I think I can deallocate all of the elements and then just call vector::clear once to make the vector size 0 and empty.
-
eerorika about 10 years@WadeG You can use clear to empty the vector, but it is redundant if you delete the vector right after that.