Qt:解构过程中的儿童生活对象

Qt: Child QObject during deconstruction?

本文关键字:生活 对象 过程中 Qt      更新时间:2023-10-16

当父QObject被解构时,它的子对象什么时候被解构?例如:

QChild* child = new QChild(master);

当我们删除master时;主的析构函数~master()将在子的析构符之前或之后调用?这里有什么秩序?

~QObject()将删除所有子项,准确的顺序可以在源代码中找到。考虑Qt源代码:

QObject::~QObject()
{
    Q_D(QObject);//now we have d-pointer
    //...
    //another code here, which for example disconnect everything
    if (!d->children.isEmpty())
        d->deleteChildren();
    //...
}

其中deleteChildren()为:

void QObjectPrivate::deleteChildren()
{
    const bool reallyWasDeleted = wasDeleted;
    wasDeleted = true;
    // delete children objects
    // don't use qDeleteAll as the destructor of the child might
    // delete siblings
    for (int i = 0; i < children.count(); ++i) {
        currentChildBeingDeleted = children.at(i);
        children[i] = 0;
        delete currentChildBeingDeleted;
    }
    children.clear();
    currentChildBeingDeleted = 0;
    wasDeleted = reallyWasDeleted;
}

另请参阅:http://www.programmerinterview.com/index.php/c-cplusplus/execution-order-of-constructor-and-destructor-in-inheritance/

另一个例子:

#include <QApplication>
#include <QDebug>
class Child: public QObject
{
public:
    Child(QObject *parent = 0) : QObject(parent)
    {}
    ~Child()
    {
       qDebug("child destroyed");
    }
};
class Parent: public QObject
{
public:
    Parent(QObject *parent = 0) : QObject(parent)
    {}
    ~Parent()
    {
       qDebug("do something here");
       qDebug("parent destroyed");
    }
};
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Parent *parent = new Parent;
    Child *child1 = new Child(parent);
    Child *child2 = new Child(parent);
    //do something
    delete parent;
    return a.exec();
}

输出:

do something here
parent destroyed
child destroyed
child destroyed

如果您将编写~Parent(){delete A; delete B;},那么正如您从输出中看到的,AB将首先被删除,子对象将更早被删除。

为什么

因为我之前建议你的规则

Inside Base constructor
Inside Derived constructor
Inside Derived destructor
Inside Base destructor

在我们的案例中,它被翻译为:

Inside QObject constructor
Inside Parent constructor
Inside Parent destructor 
Inside QObject destructor//don't forget that only ~QObject delete children, not a ~Parent

父级的析构函数的执行将在子级析构函数之前开始,并在子级被销毁之后结束。