IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)

QEnableSharedFromThis Class

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

This class was introduced in Qt 5.4.

Article lu   fois.

L'auteur

Liens sociaux

Viadeo Twitter Facebook Share on Google+   

QEnableSharedFromThis Class

  • Header: QEnableSharedFromThis

  • Since: Qt 5.4

  • CMake:

    find_package(Qt6 REQUIRED COMPONENTS Core)

    target_link_libraries(mytarget PRIVATE Qt6::Core)

  • qmake: QT += core

  • Inherited By:

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:

 
Sélectionnez
    class Y: public QEnableSharedFromThis&lt;Y&gt;
    {
    public:
        QSharedPointer&lt;Y&gt; f()
        {
            return sharedFromThis();
        }
    };

    int main()
    {
        QSharedPointer&lt;Y&gt; p(new Y());
        QSharedPointer&lt;Y&gt; y = p-&gt;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:

 
Sélectionnez
    class ScriptInterface : public QObject
    {
        Q_OBJECT

        // ...

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

Member Function Documentation

 

[since 5.4] 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.

This function was introduced in Qt 5.4.

[since 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.

Vous avez aimé ce tutoriel ? Alors partagez-le en cliquant sur les boutons suivants : Viadeo Twitter Facebook Share on Google+