-2

When looking at Qt examples (on Qt documentation like movieplayer example, or here), I never see the member destructors explicitly called.

A class definition is like:

class foo : public QParent {
    Q_OBJECT
    QStuff stuff;
    foo (QWidget *parent) : QParent(parent)
    {
         stuff = new QStuff(this);
    }
}; 

My problem is that I never see something like delete stuff;

So my questions are:

  • Are QObject derived class instances which parent is not NULL automatically deleted when their parent is?

  • Is it dangerous to delete a QObject derived member without setting it to NULL?

I guess the answers are Yes and No, but I'm not sure.

Mathieu
  • 8,840
  • 7
  • 32
  • 45
  • 3
    `stuff = new QStuff(this);` would be invalid because `stuff` is not a pointer. Also see [QT Object Trees & Ownership](http://doc.qt.io/qt-5/objecttrees.html) – user7860670 May 16 '18 at 09:51

2 Answers2

4

For the first question yes. You can check the Qt docs here where it is stated clearly:

QObjects organize themselves in object trees. When you create a QObject with another object as parent, the object will automatically add itself to the parent's children() list. The parent takes ownership of the object; i.e., it will automatically delete its children in its destructor. You can look for an object by name and optionally type using findChild() or findChildren().

For the second question, the answer deserves a little bit more of explanation. If you have QObject pointers members that are not children of your object, you have to handle their disposal manually in the destructor of your class.

You can in theory use delete on any QObject* to invoke its destructor, but since Qt objects have a powerfull event system based on signals/slots, you must be aware of the interactions with event loops. If you brutally delete a QObject connected to another QObject while the latter one is still processing a signal coming from the first one, you may end up with some problems.

This holds in both mono and multi-threaded applications. You should therefore avoid the use of delete in favor of QObject::deleteLater() that will defer the deletion of the QObject until all the signal/slots related to it have been processed.

Lastly, in the context of the implementation of a destructor it doesn't really matter if you set the pointer to null, because it will be unavailable for further use anyway. It may be important if you delete the pointee in some other method, while your instance is still alive, and you set the pointer to null to flag it as uninitialized.

Gabriella Giordano
  • 1,188
  • 9
  • 10
1

No, you do not need to delete member objects. They will get destroyed automatically when the parent class object gets destroyed.

See this FAQ.

In the case of Qt QObject pointer members, then the parent is the owner and is responsible for deleting the QObject. See here.

Paul Floyd
  • 5,530
  • 5
  • 29
  • 43