0

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?

BDL
  • 18,169
  • 14
  • 45
  • 47
Lennart Rolland
  • 7,561
  • 6
  • 47
  • 80

1 Answers1

3

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();
mohabouje
  • 3,457
  • 1
  • 13
  • 26
  • Right. It's a good practice for classes like this to not have a public constructor but instead to have a `static QSharedPointer create();` function so nobody can make a `MyClass` that isn't managed by a `QSharedPointer`. Related: To have the c'tor be (effectively) private while having `MyClass::create()` use `QSharedPointer::create()`, see https://stackoverflow.com/a/8147326 for a clever pattern. – Ben Apr 11 '19 at 12:35