3

Qt reference for QObject destructor says:

All signals to and from the object are automatically disconnected, and any pending posted events for the object are removed from the event queue. However, it is often safer to use deleteLater() rather than deleting a QObject subclass directly.

...

Warning: Deleting a QObject while pending events are waiting to be delivered can cause a crash. You must not delete the QObject directly if it exists in a different thread than the one currently executing. Use deleteLater() instead, which will cause the event loop to delete the object after all pending events have been delivered to it.

Notice the bold lines in above section.

So the question is: Are the pending posted events removed from the event queue or not?

agnor
  • 259
  • 1
  • 3
  • 12

1 Answers1

4

Warning: Deleting a QObject while pending events are waiting to be delivered can cause a crash. You must not delete the QObject directly if it exists in a different thread than the one currently executing.

You're focussing on the first statement of that sentence and ignoring the second. This situation concerns deletion of an object that exists in a different thread - (different thread affinity).

If, for example you're running on the main (GUI) thread and have an object in a 2nd thread, deleting the other object from the main thread would likely cause a crash.

If the object you're deleting is running in the thread from which it is being deleted, then yes, any pending posted events for the object are removed from the event queue.

Let's think about what's going on.

When an object calls a signal, if the receiver of the object is in the same thread as the callee, the function is called immediately (assuming the connection type is Automatic, or Direct).

If the receiver of the object has different thread affinity, an auto connection results in a Queued-Connection; rather than calling the function directly, an event is posted to the event queue of the thread for the receiving object.

When it comes to deleting the object, if we're calling the delete from a different thread, it can't access the other thread's event queue to remove pending events. More importantly, it's not thread safe and may result in a crash.

TheDarkKnight
  • 27,181
  • 6
  • 55
  • 85
  • Thanks, @TheDarkKnight. Let's rephrase the question a little: If QObject exist only in one thread, then it is safe to call delete as much as it is safe to call deleteLater? – agnor Jun 04 '15 at 08:52
  • 2
    That depends on the point in the code at which you're deleting the object. If the code is in a slot function, then [you should call deleteLater](http://stackoverflow.com/questions/22376298/when-to-use-deletelater/22378104#22378104) – TheDarkKnight Jun 04 '15 at 08:58