How delete and deleteLater works with regards to signals and slots in Qt?

Deleting QObjects is usually safe (i.e. in normal practice; there might be pathological cases I am not aware of atm), if you follow two basic rules:

  • Never delete an object in a slot or method that is called directly or indirectly by a (synchronous, connection type “direct”) signal from the object to be deleted.
    E.g. if you have a class Operation with a signal Operation::finished() and a slot Manager::operationFinished(), you don’t want delete the operation object that emitted the signal in that slot. The method emitting the finished() signal might continue accessing “this” after the emit (e.g. accessing a member), and then operate on an invalid “this” pointer.

  • Likewise, never delete an object in code that is called synchronously from the object’s event handler. E.g. don’t delete a SomeWidget in its SomeWidget::fooEvent() or in methods/slots you call from there. The event system will continue operating on the already deleted object -> Crash.

Both can be tricky to track down, as the backtraces usually look strange (Like crash while accessing a POD member variable), especially when you have complicated signal/slot chains where a deletion might occur several steps down originally initiated by a signal or event from the object that is deleted.

Such cases are the most common use case for deleteLater(). It makes sure that the current event can be completed before the control returns to the event loop, which then deletes the object. Another, I find often better way is defer the whole action by using a queued connection/QMetaObject::invokeMethod( …, Qt::QueuedConnection ).

Leave a Comment