Home > Enterprise >  Why connect `QThread::finished` signal to `QObject::deleteLater`?
Why connect `QThread::finished` signal to `QObject::deleteLater`?

Time:12-03

I read this in the Qt 5.15 documentation for QThread::finished:

When this signal is emitted, the event loop has already stopped running. No more events will be processed in the thread, except for deferred deletion events. This signal can be connected to QObject::deleteLater(), to free objects in that thread.

However, in another section of the documentation, it says that

Calling delete on a QObject from a thread other than the one that owns the object (or accessing the object in other ways) is unsafe, unless you guarantee that the object isn't processing events at that moment [emphasis mine].

If I'm understanding this correctly, after QThread::finished is emitted, the event loop has already stopped running, and if no deferred deletion events exist (i.e. QObject::deleteLater hasn't been called), all objects in the thread should have finished processing events as well. So why bother using QObject::deleteLater for these objects instead of just manually deleting them? I have no problem with using QObject::deleteLater; I'm just making sure my understanding of Qt is correct.

CodePudding user response:

QObject::deleteLater in this case is essentially just erring on the side of caution. There's no reason you couldn't simply delete the objects if you're absolutely certain there's no chance the object will be accessed.

In practice though you'll save way more time simply using QObject::deleteLater and letting Qt take care of it for you, compared to the hassle of debugging some random-seeming crash during runtime or on exit because there happens to be an access to an object you manually deleted.

  • Related