PDA

View Full Version : Enable shared from this QObject



mentalmushroom
8th September 2016, 10:04
As far as I read in the documentation in order to be able to obtain QSharedPointer from within the object itself it is necessary to inherit from QEnableSharedFromThis. This makes me think of the case when the class must inherit from another class, e.g. QObject:



class MyObject : public QObject, public QEnableSharedFromThis<MyObject>
{
public:
void addChild(MyObject *child)
{
child->parent = sharedFromThis();
}

private:
QWeakPointer<MyObject> parent;
};

QSharedPointer<MyObject> myObject(new MyObject);
myObject->addChild(QSharedPointer<MyObject>::create().data());


Is it a correct approach? Multiple inheritance is often discouraged, but I don't see another way of doing this.

anda_skoa
8th September 2016, 10:37
QObject has that built in, see QObject::setParent(), QObject::parent(), QObject::children(), etc.

Cheers,
_

mentalmushroom
8th September 2016, 11:13
Well, QObject is for example here. It might have been another class.
Also in case of QObject, it does not always have a parent, then we have a kind of mix of smart pointers with Qt parent/child model, which I'm not sure if it's good:


QSharedPointer<MyObject> myObject(new MyObject); // smart pointer
myObject->addChild(new MyObject); // naked pointer

anda_skoa
8th September 2016, 13:01
Well, QObject is for example here. It might have been another class.

In the general case that looks like the way to go.



Also in case of QObject, it does not always have a parent, then we have a kind of mix of smart pointers with Qt parent/child model, which I'm not sure if it's good:

Indeed, only hold smart pointers to the top level node of a QObject tree.

I was just pointing out that QObject is inherently capable of forming a parent/child tree with parent deleting it children when it is being deleted.

Cheers,
_