[Development] On QML, ownership, QObject-trees and QSharedPointer

Alberto Mardegan mardy at users.sourceforge.net
Thu May 24 10:46:05 CEST 2012

On 05/23/2012 02:43 PM, Thiago Macieira wrote:
> My original solution was to have a parent only deref its children's shared 
> pointer counter, deleting it only if it became zero. That means that if you 
> had a QSharedPointer to an object in the middle of the hierarchy, that object 
> would be orphaned instead of deleted when the parent died. The converse was 
> that when the last QSharedPointer reference to a QObject went away, the object 
> might survive if it still had a parent.

Nice! However, a very hard thing to do as an aftertought. IMHO, it would
be easier if the reference count was built in QObject itself, and
QSharedPointer<QObject> would just play with that reference count.
Then you would also be able to make the "delete" operator work
consistently with reference-counted QObjects, by overriding it and make
it just decrement the count (and delete the object if the count is 0).

However, I didn't think it thoroughly through, and I'm sure there would
be issues with this approach as well. But indeed I'm convinced that
using QSharedPointer and the unmodified really-deleting delete operator
in the same code is also a recipe for disaster.

> There were a few problems with that solution. I can remember now:
> 1) it didn't play very well with QWidgets after the Alien project. QWidgets 
> often reference the top-level window, which is the ultimate parent widget (the 
> one with no parents). Orphaning a QWidget from QWidget's destructor was a 
> recipe for disaster, since the original TLW data might have been gone already.
> 2) it didn't play very well with QObject siblings talking to each other during 
> destruction or, worse, deleting each other. This is a huge pain and source of 
> complexity during QObject infanticide.

Indeed, all code which assumes that the parent object is always there
should be fixed to gracefully handle being orphaned.

> 3) what happens if you had a QSharedPointer<QObject> with a parent, dropped 
> the last QSharedPointer reference (it survives because of the parent) and 
> later orphaned that object via setParent(0)? Should it be deleted?

Unless the code calling object->setParent(0) still has a reference to
the object, yes.


http://blog.mardy.it <- geek in un lingua international!

More information about the Development mailing list