Reputation: 9648
I have a class MyClass
that should be able to return this wrapped in QSharedPointer<MyClass>
.
It is my understanding (and experience) that simply creating new instances of QSharedPointer<MyClass>(this)
is NOT the way to go. Instead The correct way to accomplish what I want is to let MyClass
inherit from QEnableSharedFromThis<MyClass>
to provide the member function sharedFromThis()
.
This member function should return this wrapped in QSharedPointer<MyClass>
without all the bad side effects that would otherwise occur.
class MyClass : public QEnableSharedFromThis<MyClass>
{
/* ... */
public:
void testSharedThis()
{
auto sp=QEnableSharedFromThis<MyClass>::sharedFromThis();
if(sp.isNull()){
qWarning()<<"SHARED POINTER TO *this* WAS NULL!";
}
}
};
void main(){
MyClass *mc=new MyClass;
mc->testSharedThis();
}
However when I run testSharedThis()
in the example above, sharedFromThis()
always returns nullptr instead of this wrapped in QSharedPointer<MyClass>
.
I am new to QEnableSharedFromThis
and I am wondering if there is something that I am missing, or what could be the cause of this?
Upvotes: 0
Views: 800
Reputation: 4050
According to the official documentation:
A base class that allows obtaining a QSharedPointer for an object already managed by a shared pointer. You can inherit this class when you need to create a QSharedPointer from any instance of a class; for instance, from within the object itself.
So you need to instantiate your pointer as smart pointer:
QSharedPointer<MyClass> mc(new MyClass());
mc->testSharedThis();
Or in your case use the equivalent to std::make_shared for Qt Smart Pointers:
QSharedPointer<MyClass> mc = QSharedPointer<MyClass>::create();
mc->testSharedThis();
Upvotes: 3