Qt QObject QObject Lifetime and Ownership


QObjects come with their own alternative lifetime concept compared to native C++'s raw,unique or shared pointers.

QObjects have the possibility to build an objecttree by declaring parent/child relationships.

The simplest way to declare this relationship is by passing the parent object in the constructor. As an lternative you can manually set the parent of a QObject by calling setParent. This is the only direction to declare this relationship. You cannot add a child to a parents class but only the other way round.

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

When parent now gets deleted in stack-unwind child will also be deleted.

When we delete a QObject it will "unregister" itself form the parent object;

QObject parent;
QObject child* = new QObject(&parent);
delete child; //this causes no problem.

The same applies for stack variables:

QObject parent;
QObject child(&parent);

child will get deleted before parent during stack-unwind and unregister itself from it's parent.

Note: You can manually call setParent with a reverse order of declaration which will break the automatic destruction.