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

Nikos Chantziaras realnc at gmail.com
Sat Aug 18 19:05:07 CEST 2012


On 18/08/12 19:38, K. Frank wrote:
> Hello List!
>
> I see the following code snippet in some Qt documentation:
>
>     QGraphicsScene scene;
>     scene.addText("Hello, world!");
>
>     QGraphicsView view(&scene);
>     view.show();
>
> (From http://doc.qt.nokia.com/4.7-snapshot/qgraphicsview.html)
>
> Both scene and view are automatic variables.  If this example were
> taken literally, would it lead to a double-destruction bug?
>
> As an automatic variable, view is destroyed when it goes out of
> scope.  Then scene goes out of scope and is destroyed.  I imagine
> that scene is the parent of view in the usual Qt sense, so that
> scene's destructor deletes view, which would be a bug.

When 'view' is destroyed (because it goes out of scope), it tells 
'scene' about it.  So scene removes it from its list of children.  A 
double delete is thus avoided.

This is possible because C++ guarantees that automatic vars are 
destroyed in the reverse order of their declaration; 'view' will always 
be destroyed before 'scene', and thus its dtor will always be able to 
communicate to 'scene' that its being destroyed.

PS:
I just googled this in order to find something to support the above 
statement.  And what I found is actually written in the Qt docs :-)

http://doc-snapshot.qt-project.org/4.8/objecttrees.html#construction-destruction-order-of-qobjects




More information about the Interest mailing list