Home How to implement class destructor with vector of pointers C++

# How to implement class destructor with vector of pointers C++

Ayaka
1#
Ayaka Published in 2018-01-10 20:42:18Z
 If I have class and vector of pointers in class how should I write destructor to properly free memory? Is it correct? ~Class() { for(int i = 0; i
user2079303
2#
 If I have class and vector of pointers in class how should I write destructor to properly free memory? Is it correct? It depends. Do the pointers point to objects that were allocated with new and is this class the owner of those dynamic objects (i.e. is this class responsible for their destruction)? If not, then it's not correct. Or should I also erase elements from vector? Your example for erasing elements of the vector is wrong. It will skip half of the elements and thus will not call delete all pointers. After first iteration, first element will have been erased, so the next element has been shifted to the index 0, but next loop deletes and erases the element in index 1. There's no point in erasing elements of the vector, because it is immediately about to be destroyed. Or any other solutions? If you intend for the class to own dynamically allocated objects, prefer using a vector of objects instead of pointers. If you need a vector of pointers for example to allow run time polymorphism, then use a vector of std::unique_ptr. That way you don't need to implement a destructor as the automatically generated would be just fine.
 If your class is to supposed to own the objects pointed to, then its sufficient to do: for (auto p : v) delete p;  If the vector itself is the member of the class then its elements are getting deleted when the class instance object is destroyed, you dont need to do this manually. And in your example you are also doing it wrong. If its a std::vector you could just call vector's clear() method. Otherwise you would call delete[] p; where p is the pointer to the vector elements itself.