Learn what Felgo offers to help your business succeed. Start your free evaluation today! Felgo for Your Business

QEnableSharedFromThis Class

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

Header: #include <QEnableSharedFromThis>
qmake: QT += core
Since: Qt 5.4

Public Functions

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

Detailed Description

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. The key point is that the technique of just returning QSharedPointer<T>(this) can not 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>
    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

    // ...

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 QSharedPointer holding a null pointer.

This function was introduced in Qt 5.4.

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

This is an overloaded function.

Const overload of sharedFromThis().

This function was introduced in Qt 5.4.

Qt_Technology_Partner_RGB_475 Qt_Service_Partner_RGB_475_padded