Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
Why deleting an QObject is dangerous?
tdiff last edited by
Documentation states that
@Warning: Deleting a QObject while pending events are waiting to be delivered can cause a crash@
and sugests using deleteLater() instead of delete.
Of course using simple delete on object that lives in another thread may cause crashes for obvious reasons. But calling delete on QObject that lives in the same thread from which delete is called should not lead to crashes since deleting QObject should remove any pending events for it in event queue. So we should never come across situation when, for example, queued signal is delivered to deleted object.
But may be I misunderstand something and deleting QObject from thread that delivers events to it is not safe? Provided we don't consider marginal cases like deleting signal sender in slot.
eyyakeen last edited by
I assume that not only deleting the object that lives in another thread causes crashes but also deleting the parent object that has childs may result unexpected results. The order should be deleting the childs first and then the parent. To prevent such a thing, it may be suggested.
QObject deletes all children automatically when delete is called.
L.MCH last edited by
It is still dangerous because default connect() behavior is Qt::AutoConnection
So if you later modify your code and some signal/slot Qt::AutoConnection connections related to that QObject are transparently redirected to a different thread (i.e previously Qt::AutoConnection was executed as Qt::DirectConnection, after source modifications it gets executed as Qt::QueuedConnection because either signal or slot are in different threads) you will start getting random crashes.
As a rule of thumb is always better to use deleteLater() because it will protect you (or whoever later will modify your source code) by this type of "automatic behavior side-effects" bugs.
Right now you may think that you just have to be careful "now", use only connect() with Qt::DirectConnection, document this fact properly and everything will be allright.
But maybe some months from now you will reuse that code knowing "it works" with some other code that behind the scenes uses a Qt::AutoConnection and you will start getting random crashes very hard to track down.