Qt:解构时的儿童QObject?

时间:2015-02-26 09:35:25

标签: c++ qt

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

QChild* child = new QChild(master);

当我们删除主人;主人的析构函数~Master()将在孩子的析构函数之前或之后调用?这是什么命令?

2 个答案:

答案 0 :(得分:3)

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

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可以看到,将首先删除它,并且之前将删除子对象。

<强>为什么吗

Because of rule which I suggested you earlier

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

答案 1 :(得分:0)

父析构函数的执行将在子析构函数之前开始,并在孩子被销毁之后完成。