虽然类派生自QObject,但是定义自己的析构函数?

LPr*_*Prc 8 c++ qt

我们有一个班级Test和一个班级AnotherClass.两者都来自QObject.

Test.h:

class Test : public QObject
{
Q_OBJECT

public:
    Test(QObject* parent);
    ~Test();

private:
    AnotherClass* other;
};

class AnotherClass : public QObject
{
Q_OBJECT

public:
    AnotherClass(QObject* parent);
    ~AnotherClass();
};
Run Code Online (Sandbox Code Playgroud)

TEST.CPP:

Test::Test(QObject* parent) : QObject(parent) 
{
    other = new AnotherClass(this);
}

Test::~Test()
{
    delete other;
}
Run Code Online (Sandbox Code Playgroud)

other应该在Test-instance被销毁时自动销毁,因为Test它是父other,对吧?

  • 现在我应该删除other通过自己在~Test()或是否处于不确定阶段退出该计划,因为它试图删除同样的对象两次?
  • 这里的正确方法是什么?

tal*_*aki 12

QObjects在对象树中组织自己.当您使用另一个对象作为父对象创建QObject时,该对象将自动将其自身添加到父对象的children()列表中.父母取得对象的所有权; 即,它将自动删除其析构函数中的子项.有关更多信息,请参阅对象树和所有权.

因为你通过这个指针测试对象AnotherClass构造它意味着你使用的测试对象的父AnotherClass.因此,删除Test对象也会删除其子对象,您不需要显式删除 其他对象.

但是,在这种情况下,析构函数中的显式删除不会导致双重删除,因为它会导致从父级的children()列表中取消注册.