Ambiguous destructor for QObject?

The Qt link for a QObject destructor says:

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

...

Warning: Deleting a QObject while waiting for pending events can fail . You should not dispose of a QObject directly if it exists on a different thread than the one currently executing. Use deleteLater () instead, which will cause the loop to delete the object after all pending events have been dispatched.

Notice the bold lines in the above section.

So the question is, are the pending dispatched events removed from the event queue or not?

+3


source to share


1 answer


Warning. Deleting a QObject while waiting for pending events may crash. You shouldn't dispose of a QObject directly if it exists on a different thread than the one currently running.

You focus on the first statement of this sentence and ignore the second. This situation concerns the deletion of an object that exists in a different thread - (different affinity of the thread ).

If, for example, you are running on the main thread (GUI) and have an object in a second thread, deleting another object from the main thread might crash.

If the object you are deleting is running on the thread it is being deleted from, then yes, any pending dispatched events for the object are removed from the event queue.



Think about what's going on.

When an object raises a signal, if the receiver of the object is on 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 a different thread affinity, the automatic connection results in a connected queue; instead of directly calling the function, the event is dispatched to the thread's event queue for the receiving object.

When it comes to deleting an object, if we call delete from another thread, it cannot access another thread's event queue to remove pending events. More importantly, it is not thread safe and can crash.

+4


source







All Articles