QEnableSharedFromThis Class | Qt Core | Qt 6.11.2
Description: A base class that allows obtaining a QSharedPointer for an object already managed by a shared pointer.

- Qt 6.11
- Qt Core
- C++ Classes
- QEnableSharedFromThis
- Qt 6.11.2 Reference Documentation

# QEnableSharedFromThis Class

template <typename T> class QEnableSharedFromThis

A base class that allows obtaining a QSharedPointer for an object already managed by a shared pointer. More...

Header: | `#include <QEnableSharedFromThis>`
CMake: | `find_package(Qt6 REQUIRED COMPONENTS Core)` `target_link_libraries(mytarget PRIVATE Qt6::Core)`
qmake: | `QT += core`

- List of all members, including inherited members

## Public Functions

QSharedPointer<T> | sharedFromThis()
QSharedPointer<const T> | sharedFromThis() const

## Detailed Description

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. The key point is that the technique of just returning QSharedPointer<T>(this) cannot be used, because this winds up creating multiple distinct QSharedPointer objects with separate reference counts. For this reason you must never create more than one QSharedPointer from the same raw pointer.

QEnableSharedFromThis defines two member functions called sharedFromThis() that return a QSharedPointer<T> and QSharedPointer<const T>, depending on constness, to `this`:

         class Y: public QEnableSharedFromThis<Y>
         {
         public:
             QSharedPointer<Y> f()
             {
                 return sharedFromThis();
             }
         };

         int main()
         {
             QSharedPointer<Y> p(new Y());
             QSharedPointer<Y> y = p->f();
             Q_ASSERT(p == y); // p and q must share ownership
         }

It is also possible to get a shared pointer from an object outside of the class itself. This is especially useful in code that provides an interface to scripts, where it is currently not possible to use shared pointers. For example:

         class ScriptInterface : public QObject
         {
             Q_OBJECT

             // ...

         public slots:
             void slotCalledByScript(Y *managedBySharedPointer)
             {
                 QSharedPointer<Y> yPtr = managedBySharedPointer->sharedFromThis();
                 // Some other code unrelated to scripts that expects a QSharedPointer<Y> ...
             }
         };

## Member Function Documentation

### QSharedPointer<T> QEnableSharedFromThis::sharedFromThis()

If `this` (that is, the subclass instance invoking this method) is being managed by a QSharedPointer, returns a shared pointer instance pointing to `this`; otherwise returns a null QSharedPointer.

### QSharedPointer<const T> QEnableSharedFromThis::sharedFromThis() const

Const overload of sharedFromThis().

This is an overloaded function.