Reputation: 4489
When the parent QObject is deconstructed, when will its children be deconstructed? For example:
QChild* child = new QChild(master);
when we delete master; the master's destructor ~Master() will be called before or after the child's destructor? What's order here?
Upvotes: 1
Views: 1046
Reputation: 18514
~QObject()
will delete all children, accurate order you can find in source code. Consider 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();
//...
}
Where deleteChildren()
is:
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;
}
Another example:
#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();
}
Output:
do something here
parent destroyed
child destroyed
child destroyed
If you will write ~Parent(){delete A; delete B;}
, then as you can see from output A
and B
will be deleted first and child objects will be deleted earlier.
Why?
Because of rule which I suggested you earlier
Inside Base constructor
Inside Derived constructor
Inside Derived destructor
Inside Base destructor
which in our case is translated to:
Inside QObject constructor
Inside Parent constructor
Inside Parent destructor
Inside QObject destructor//don't forget that only ~QObject delete children, not a ~Parent
Upvotes: 3
Reputation: 49299
Execution of the parent's destructor will begin before the child destructor, and will finish after the child has been destroyed.
Upvotes: 0