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

K. Frank kfrank29.c at gmail.com
Sat Aug 18 18:38:43 CEST 2012


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.

(I believe that I have seen other code snippets in the Qt documentation
that have this same issue.)

Is this just poetic code-snippet license?  Are scene and view not in
a conventional Qt parent-child relationship?

The documentation shows the constructor as:

   QGraphicsView ( QWidget * parent = 0 )

Of course, you can call arguments anything you want, but the name
"parent" is suggestive.

Or is the code okay, and there is something I'm missing about
the whole Qt parent-child-ownership-destruction mechanism?

(By the way, I'm looking at QGraphicsScene / QGraphicsView in
follow-up to some suggestions on the list to use them for Qt 2-d
game programming.)

Thanks.


K. Frank



More information about the Interest mailing list