Про QObject::deleteLater()
От: m2user  
Дата: 08.10.25 11:24
Оценка: 1 (1)
Собственно вопрос, в каких случаях следует применять deleteLater(), а в каких применим delete.
А также что делать с объектами, созданными на стеке — когда их можно использовать в слотах/сигналах.

В документации по QObject написано:
(https://doc.qt.io/qt-6/qobject.html#dtor.QObject)

QObject::~QObject()
Destroys the object, deleting all its child objects.
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: All child objects are deleted. If any of these objects are on the stack or global, sooner or later your program will crash. We do not recommend holding pointers to child objects from outside the parent.
If you still do, the destroyed() signal gives you an opportunity to detect when an object is destroyed.


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.


Фраза "exists in a different thread" по-видимому означает, что объект используется из другого потока.
Т.е. это не про thread affinity, где используется термин "lives in" (A QObject instance is said to have a thread affinity, or that it lives in a certain thread).

Как я понимаю, проблема будет в случае, если в момент вызова delete уже выполняется один из подключенных слотов/сигналов?
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.