[Qt-interest] QObject::deleteLater and private event loop (not using QCoreApplication::exec())

Bo Thorsen bo at fioniasoftware.dk
Fri Jun 10 13:53:45 CEST 2011


Den 10-06-2011 13:27, Nikos Chantziaras skrev:
> On 06/10/2011 11:45 AM, Thiago Macieira wrote:
>> On Friday, 10 de June de 2011 10:11:17 Zeljko wrote:
>>> Hi al,
>>> When reading docs about processEvents() it says that
>>> DeferredDelete events won't be processed if we use
>>> our own event loop, so does it
>>> mean that deleteLater() won't destroy that object ?
>>> What should I do if it is so ? call
>>> sendPostedEvents(0, QEvent::DeferredDelete) after
>>> deleteLater() or what ? Is it ok to call sendPostedEvents(0,
>>> QEvent::DeferredDelete) before call to
>>> processEvents() in my own loop ?
>>
>> 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.

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.

With your example, you know that the object is deleted immediately, so 
you will be more careful what you do.

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++ :)

Bo Thorsen,
Fionia Software.

-- 

Expert Qt and C++ developer for hire
Contact me if you need expert Qt help
http://www.fioniasoftware.dk



More information about the Qt-interest-old mailing list