Enable shared from this QObject
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:
Code:
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.
Re: Enable shared from this QObject
Re: Enable shared from this QObject
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:
Code:
QSharedPointer<MyObject> myObject(new MyObject); // smart pointer
myObject->addChild(new MyObject); // naked pointer
Re: Enable shared from this QObject
Quote:
Originally Posted by
mentalmushroom
Well, QObject is for example here. It might have been another class.
In the general case that looks like the way to go.
Quote:
Originally Posted by
mentalmushroom
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,
_