[Qt-interest] Memory Management in Qt

Oliver.Knoll at comit.ch Oliver.Knoll at comit.ch
Tue Oct 26 10:33:37 CEST 2010


On 2010-10-26 Andre Andre Somers wrote:

> ...
> Qt does not completely free you of memory management, but it is not 
> often that you need to manually delete instances of Qt classes.

But always keep in mind that you /can/ delete children manually ;) The Qt QObject parent/child model also takes care of that ("the child notifies its parent upon deletion").

A good example where you might want to do that is when you (for whatever reasons) you want to create a QFileDialog on the heap (using new()). Most often the parent would be the QMainWindow - but that parent object normally lives for the entire lifespan of the application, and hence only gets deleted itself when the user quits the application (well, isn't that obvious ;)

So normally a user calls "Open file" several times, and each time a QFileDialog would be instantiated - and never deleted, until the application quits. So memory consumption would grow and grow... technically that is not a memory leak, since the memory is still being referenced by the QMainWindow instance! It is much the same problem when in Java you don't set unused references explicitly to 'null': some object might still live for the entire application lifetime and reference those (unused) objects, and the garbage collector hence never gets a chance to remove them!

I agree, this example is somewhat artificial (normally you would instantiate a QFileDialog on the stack, and not on the heap, so problem solved :).


But the message here is: always think of how long the parent is going to live, and whether the child is needed for the entire lifetime of its parent. If not, you might want to explicitly delete the child first (and "Yes, you CAN!" ;)

Off course there are some caveats as well: some QObjects need to "survive" for a guaranteed lifespan, for example in the "Qt networking area" (e.g. "a network reply object must not be deleted in the slot where it is delivered"). As always study the Qt documentation, it tells you when you must not delete an object, or call deleteLater() (inside a slot typically, which is called whenever the network receives a packet, for instance...). But these are few places in Qt and really the exception...

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






More information about the Qt-interest-old mailing list