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

Olivier Goffart olivier at woboq.com
Thu May 24 16:33:53 CEST 2012

On Wednesday 23 May 2012 13:43:22 Thiago Macieira wrote:
> On quarta-feira, 23 de maio de 2012 14.16.12, Alberto Mardegan wrote:
> > On 05/23/2012 01:25 PM, Rene Jensen wrote:
> > > Question: How can we expose objects governed by QSharedPointer to QML
> > > safely? I can guarantee the lifecycle beyond the life of my
> > > QDeclarativeEngine.
> > 
> > As neither of us knows exactly how QML handles QSharedPointer (my guess
> > is that it simply doesn't; QSharedPointer is a template class which can
> > be used with many other types than QObject, so I don't think that
> > exposing it in QML is trivial), I would simply recommend you not to use
> > it.
> > I actually mentioned QSharedPointer in a recent blog post of mine [0],
> > which you might find interesting especially if your use of
> > QSharedPointer is suggested by your previous experience with other
> > toolkits. If you really think that QSharedPointer is absolutely necessary
> > in your case (I still doubt), then just expose its QObject data to QML,
> > since you also claim that you can make sure its lifetime will survive the
> > engine.
> Just a tidbit...
> I've long wanted to make QSharedPointer on QObject-derivatives participate
> in the whole-tree ownership, somehow. I introduced QSharedPointer in 4.4
> and I did some work in 4.5 to make that work.
> 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.

So that would be like having "children" be in implemented as a 
QList<QSharedPointer<QObject> > ?

But I personaly think it shoud not be the case.  QSharedPointer is orthogonal 
with object tree as much as it is orthogonal with std::shared_ptr or 
QScopedPointer or manually delete.

You have to pick how you do thememory management for a given pointer and stick 
to it.


Woboq - Qt services and support - http://woboq.com

More information about the Development mailing list