[Qt-interest] QObject::deleteLater and private event loop (not using QCoreApplication::exec())
Nikos Chantziaras
realnc at arcor.de
Fri Jun 10 14:19:33 CEST 2011
On 06/10/2011 02:53 PM, Bo Thorsen wrote:
> Den 10-06-2011 13:27, Nikos Chantziaras skrev:
>> On 06/10/2011 11:45 AM, Thiago Macieira wrote:
>>> [...]
>>> deleteLater() events (DeferredDelete) are handled specially, to avoid
>>> something like:
>>>
>>> obj->deleteLater();
>>> obj->something();
>>> run a dialog
>>> obj->somethingElse(); // crash here
>>
>> Just out of curiosity, why would anyone try to avoid the above? It
>> looks exactly like trying to avoid:
>>
>> delete obj;
>> obj->something();
>>
>> It's the same kind of coding mistake.
>
> Not exactly. The point of deleteLater is that you know the object will
> be deleted some time after the function returned - how long exactly is
> irrelevant.
It doesn't look very irrelevant to me though, simply because of the
nature of the word "irrelevant." Meaning that once you call
deleteLater(), you shouldn't call anything else on that object since you
don't know when it's going to be deleted.
> But with any kind of QEventLoop->exec (for example in an error message
> some other place in the code), your knowledge wouldn't hold, unless this
> rule was in place.
Then why call deleteLater() in the first place? Only call it when
you're done with the object.
> Exactly because it's completely irrelevant when the object is deleted,
> as long as it just happens sometime, there is no reason not to avoid a
> subtle and very hard to find bug. This is good framework design to me.
>
> Of course, in some ways you are correct. But hey, there's a safety on
> guns too, so you don't shoot yourself in the foot - real life or C++ :)
It looks a bit the opposite to me. That is, not good design. In this
case, calling any member of obj after deleteLater() should probably
crash the program. That way you know immediately, rather than hoping
that obj->something() might not fire-up an event loop or anything. To
use Thiago's original example:
obj->deleteLater();
obj->something(); // runs a dialog
run a dialog // crash here
obj->somethingElse(); // we crashed above so we don't reach this
More information about the Qt-interest-old
mailing list