当父QObject被解构时,其子对象何时被解构?
例如:

QChild* child = new QChild(master);

当我们删除母版时;主机的析构函数〜Master()将在 child 的析构函数之前或之后被调用?这里点什么?

最佳答案

~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

关于c++ - Qt:子QObject在解构期间?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28738810/

10-11 23:16