[Interest] Double destruction of Qt objects in Qt example code?

André Pönitz andre.poenitz at mathematik.tu-chemnitz.de
Sat Aug 18 22:21:06 CEST 2012


On Sat, Aug 18, 2012 at 09:29:53PM +0300, Nikos Chantziaras wrote:
> On 18/08/12 20:46, K. Frank wrote:
> > [...]
> > This does raise one c++ / Qt question for me:  When an automatic
> > variable goes out of scope, its destructor is called (and, at some
> > point, the stack is popped, but not by the destructor nor by any
> > explicit user code).  When a heap variable is deleted, its destructor
> > is called, and the equivalent of free is called.  The point is delete
> > is not called (in correct code) on automatic variables.
> >
> > How can the Qt parent-child system work with both automatic and
> > heap variables as children?  When a child object registers itself
> > with its parent (e.g., by being passed a pointer to its parent in its
> > constructor), neither the child object nor the parent knows whether
> > the child is an automatic or heap variable (and, using portable
> > standard c++, can't know).  So how can the parent know (when the
> > parent is destroyed) whether to call the child's destructor directly or
> > to call delete on the child?
> 
> Qt doesn't detect this.  Your application will crash.  So don't do it :-)
> 
> On a similar note, don't delete QObject instances manually.  Call their 
> deleteLater() member function instead.

There are only rare cases where deleteLater is needed. 
Otherwise, using it is unneeded overhead. 

Andre'



More information about the Interest mailing list