Memory management in Qt?

If you build your own hierarchy with QObjects, that is, you initialise all newly created QObjects with a parent,

QObject* parent = new QObject();
QObject* child = new QObject(parent);

then it is enough to delete the parent, because the parents destructor will take care of destroying child. (It does this by issuing signals, so it is safe even when you delete child manually before the parent.)

You could also delete the child first, the order doesn’t matter. For an example where the order does matter here’s the documentation about object trees.

If your MyClass is not a child of QObject, you’ll have to use the plain C++ way of doing things.

Also, note that the parent–child hierarchy of QObjects is generally independent of the hierarchy of the C++ class hierarchy/inheritance tree. That means, that an assigned child does not need to be a direct subclass of it’s parent. Any (subclass of) QObject will suffice.

There might be some constraints imposed by the constructors for other reasons, however; such as in QWidget(QWidget* parent=0), where the parent must be another QWidget, due to e.g. visibility flags and because you’d do some basic layout that way; but for Qt’s hierarchy system in general, you are allowed to have any QObject as a parent.

Leave a Comment