Friday, March 26, 2010

QObject::deleteLater() - the best way to hide bugs

The method deleteLater() is very often used to avoid application crashes. In fact in most cases it just hides the real problem! Qt provides several methods to avoid dangling pointers and control objects lifetime. For example QObject::setParent can be used or "destroyed" signal. Developers should use them and really dig to the problem, understand what is going on in their product.

Additionally it is important to remember that deleteLater() works only if a main loop (qapp.exec()) of an application is already running or is going to be started after the call. Otherwise the object won't be deleted. In some cases even if there is no memory leaks when a program is running objects might not be cleaned before the program exists. In general it is not a problem since the memory will be freed by the system. Unfortunately it is not possible for valgrind to check if this is the case what basically means that it will report many memory leaks. It is then time consuming to investigate which leaks are real.

http://doc.trolltech.com/4.6/qobject.html#details
http://doc.trolltech.com/4.6/objecttrees.html
http://doc.trolltech.com/4.6/qobject.html#dtor.QObject
http://doc.trolltech.com/4.6/qobject.html#deleteLater

No comments: