简体   繁体   English

如何使用指针向量实现类析构函数C ++

[英]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)? 指针是否指向分配了new对象,并且此类是这些动态对象的所有者(即,该类负责它们的销毁)吗? 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. 它会跳过一半的元素,因此不会调用delete所有指针。 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. 第一次迭代后,第一个元素将被擦除,因此下一个元素已移至索引0,但是next循环删除并擦除了索引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 . 例如,如果需要指针向量来允许运行时多态性,请使用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. 如果它是std :: vector,则可以调用vector的clear()方法。 Otherwise you would call delete[] p; 否则,您将调用delete [] p; where p is the pointer to the vector elements itself. 其中p是指向向量元素本身的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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