如何在类中删除实例类

How to delete instance class inside class

本文关键字:删除 实例      更新时间:2023-10-16

考虑以下代码片段:

#include <iostream>
using namespace std;
class X {
  public:
    class Z {
      public:
        void f() {
          cout << "Z().f()" << endl;
        }
    };
    class Y {
      public:
        int A;
        Y(int x) {
          A = x;
        }
        int c() {
          return A;
        }
    };
    public:
      Z* z;
      // How to free Y instance ?
      Y* a(int x) {
        Y* y = new Y(x);
        return y;
      }
    public:
      X() {
        z = new Z();
      }
      ~X() {
        delete z;
      }
};
int main(void) {
  int a;
  X* x = new X();
  cout << "input :" << endl;
  cin >> a;
  cout << "result : " << x->a(a)->c() << endl;
  x->z->f();
  delete x;
  return 0;
}

虽然Z对象可以很容易地在~X()上释放,我很好奇如何释放Y一个?因为我没有分配任何变量来保存它的内存地址。

顺便说一下,这种东西的术语是什么?x -> c () () ->

谢谢。:)

// How to free Y instance ?
Y* a(int x) {
  Y* y = new Y(x);
  return y;
}

问题是,从函数原型来看,谁负责删除实例并不清楚。但是,由于只有调用方拥有实例的句柄,因此删除应该是被调用方的责任。这应该被很好的记录下来。但最好的方法是使用具有正确所有权语义的智能指针。在这种情况下,std::unique_ptr<Y>似乎是一个合适的匹配,使用它的事实使意图明确,消除了有关所有权的文档的需要:

std::unique_ptr<Y> a(int x)
{
  return std::unique_ptr<Y>( new Y(x) );
}

从函数返回内存,因此由调用者来删除它:

X x;
Y *ptr = x.a(5);
delete ptr;

希望你永远不会做这样的事情。如果你必须这样做,那么建议你使用智能指针,如shared_ptrunique_ptr

std::unique_ptr<Y> a(int x) {
  return std::unique_ptr<Y>(new Y(x));
}

这样,就不必担心删除实例,因为指针类的析构函数承担了删除实例的责任。