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

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<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);
  }
}
user2079303
2#
user2079303 Reply to 2018-01-10 20:55:32Z

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.

StPiere
3#
StPiere Reply to 2018-01-10 21:58:15Z

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.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.257462 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO