8.6.  QObject Lifecycle

[ fromfile: qobject-lifecycle.xml id: qobject-lifecycle ]

This section describes a few best practices for managing the QObject lifecycle.

[Warning] No static QObjects

It is important to ensure that every QObject you construct is created after the QApplication, and destroyed before the QApplication is destroyed. Objects created in static storage are destroyed after main() has returned, which is too late. This means you should never define static storage-class QObjects.[73]

[Important] Stack or Heap?

In general, a QObject without a parent should be created on the stack or defined as an subobject of another class. A QObject with a parent should not be on the stack because then it might get deleted twice accidentally. All QObjects created on the heap should either have a parent, or be managed somehow by another object.

[Tip] deleteLater()

It is not recommended to delete QObjects directly. In a program with an event loop, it is better to use QObject::deleteLater(). This schedules the object to be destroyed when the application is processing events, for example, if you have called it from a slot, after your current slot returns.

This is actually required from slots where you may wish to delete the sender() of a signal.[74]



[73] Storage class is discussed in Section 20.3.

[74] Example 17.21 has an example of this usage.