The question is old, but I'll leave this for the future generation)
The reply which was marked as an answer is correct but oddly formulated.
Actually your question contains a right answer:
message loop already ends with the return from a.exec? Thus the
deletion event will never be processed, in fact not even pushed into a
message queue since there is none.
This is exactly what is happening. Everything deleteLater()
does is just posting a deletion event into the outter event loop. When event gets proccessed - object gets deleted. But if there are not outter event loop and no event loop is encountered later in the execution flow - event will never get posted, thus object is never deleted.
If you call deleteLater()
in the object's destructor and put an object on the stack - deleteLater()
is called when the object goes out of scope. In your example "going out of scope" is happening when closing brace of main()
function is encountered. However, by that time, a.exec()
(which represents the main event loop of Qt App) has already returned --> no event loop any more --> deleteLater()
was called, but it's nowhere to post a deletion event --> objects were supposed to be "deletedLater" never get deleted...
Regarding the part "when to use deleteLater()":
Kuba Ober answered:
Generally speaking, there is a narrow set of circumstances where
deleteLater should be used. Most likely you simply shouldn't be using
it...
Don't listen to it, it is absolutely incorrect as the whole answer. What you should do and what should not you better decide after reading this article. Although, it is mainly about Qt threads, the article also tells about ascynchronous programming (and, as Emerald Weapon mentioned, it is exactly what deleteLater() was created for).
Also, smart pointers and QObject parent ownership have nothing to do with scheduling for the deletion with deleteLater()
. These both techniques are actually using a simple delete
operation under the hood. And as the article shows and as Emerald Weapon's answer demonstrated: delete
does not solve the problems deleteLater()
does. So if you need to delete object you use delete
, if you need to schedule it for the deletion you use deleteLater()
.
BTW, if you want to use smart pointer with deleteLater()
you can specify the deleter:
// Shared Pointer
QSharedPointer<MyObject> obj =
QSharedPointer<MyObject>(new MyObject, &QObject::deleteLater);
// Scoped Pointer
QScopedPointer<MyObject, QScopedPointerDeleteLater> customPointer(new MyObject);
And at last, It is an NOT an error to use deleteLater()
in the destructor of QObject
, for non-child objects.