[Qt-interest] Memory Management in Qt

Oliver.Knoll at comit.ch Oliver.Knoll at comit.ch
Fri Oct 29 11:23:06 CEST 2010


On 2010-10-28 Daniel Daniel Price wrote:

>> So normally a user calls "Open file" several times, and each time a QFileDialog
> would be instantiated - and never deleted, until the application quits.
> 
> See Qt::WA_DeleteOnClose.

Yes, that is another possibility to tell the dialog / window to delete itself once it is closed. But since it is an optional flag you need to remember using it just like you should remember to delete a dialog otherwise (when not setting that flag), if you want to make sure that resources are released as soon as they are not needed anymore.

> 
>> I agree, this example is somewhat artificial (normally you would
>> instantiate a QFileDialog on the stack, and not on the heap, so
>> problem solved :).
> 
> I hope not. This is now considered bad practice. You should create the dialog on
> the heap and connect to the signals it emits. You should not assume that the
> parent window out-lives the dialog! It is very easy to crash most Qt applications (at
> least on X11) by killing the main window while a model dialog is shown. Same thing
> for contextual menus. See
> 
> http://labs.qt.nokia.com/2010/02/23/unpredictable-exec/

Good link, I was not aware of these issues! But since a QFileDialog is typically modal (blocking all other windows / dialogs, until the user has chosen a file) at least the danger of closing the parent window (main window) of such a file dialog is not present; at least not via the normal GUI way - but thinking a bit more about it the application could receive a network packet in the meantime (which is still being processed, as the event queue is still running, even though you might think exec() is blocking your own code and nothing else happens until your own method returns!), saying "Terminate application", and then you would have the same problem: the application would be closed and the file dialog on the stack would cause memory trouble when its parent is deleted!

So it seems now The Way To Go(tm) now is to:

- Always create widgets on the heap (to avoid memory corruption when parent is deleted)
  (which can also happen for MODAL (aka blocking) dialogs - Qt event queue is still running!)

- Call QDialog http://doc.trolltech.com/4.7/qdialog.html#open (instead of exec()), as to avoid re-entering the Qt event loop)


Cheers, Oliver
--
Oliver Knoll
Dipl. Informatik-Ing. ETH
COMIT AG - ++41 79 520 95 22






More information about the Qt-interest-old mailing list