简体   繁体   中英

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

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<v.size(); i++)
  {
    delete v[i];
  }
}

Or should I also erase elements from vector? Or any other solutions?

~Class()
{
  for(int i = 0; i<v.size(); i++)
  {
    delete v[i];
    v.erase(e.begin() + i);
  }
}

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 (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM