[solved] deleteLater() ?
-
Hello
I'm wondering, when precisely does the "deleteLater()" function remove the object? The documentation says:"The object will be deleted when control returns to the event loop. If the event loop is not running when this function is called (e.g. deleteLater() is called on an object before QCoreApplication::exec()), the object will be deleted once the event loop is started."
But I can't understand what this means... I'd appreciate if someone could give a "for dummies" explanation when the deletion happens and if there is some particular case in which it never deletes it...Thanks
- Richard
-
deleteLater() posts an event to the event queue (like a repaint event, a timer event or a network event). If the event is processed it deletes the object.
If there is no event loop your object isn't deleted.
-
delete removes an object right at the time you call it. deleteLater calls delete on an object after all the events currently pending in the event loop are handled.
Imagine some object A reacting to some event in Qt (let's say a mouse click). A calls B::someMethod() which contains "delete A;". This code will crash: After B::someMethod() returns, code in object A will be executed.
"deleteLater(A);" on the other hand is save: A is still around after B::someMethod() returns. Only after the execution of the original mouse click is done and the Qt eventloop is executing again (== there is nothing to do) Qt will delete A.
Does that help?
-
Yes it does, :) I was facing a crash after a long button press (deleted the object after timeout) and the issue was probably that there was some action referring to the object active in the queue. Adding delete later solved the issue, and I added a qdebug to the deconstructor just to be sure it is deleted, as so it is. Thank you.
- Richard