QEnableSharedFromThis Class

template <typename T> class QEnableSharedFromThis

既に共有ポインターで管理されているオブジェクトのQSharedPointer を取得するための基底クラスです。詳細...

ヘッダー #include <QEnableSharedFromThis>
CMake: find_package(Qt6 REQUIRED COMPONENTS Core)
target_link_libraries(mytarget PRIVATE Qt6::Core)
qmake: QT += core

パブリック関数

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

詳細説明

あるクラスのインスタンスからQSharedPointer を作成する必要がある場合、このクラスを継承することができる。重要な点は、QSharedPointer<T>(this)をただ返すというテクニックは使えないということです。これは、別々の参照カウントを持つ複数の異なるQSharedPointer オブジェクトを生成してしまうことになるからです。このため、同じ未加工ポインタからQSharedPointer

thisQEnableSharedFromThisは、QSharedPointer<T>とQSharedPointer<const T>を返すsharedFromThis()と呼ばれる2つのメンバ関数を定義しています(constnessによって異なります):

    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
    }

クラス自身の外部にあるオブジェクトから共有ポインタを取得することも可能です。これは、スクリプトへのインタフェースを提供するコードで特に有用で、現在のところ共有ポインタを使用することはできません。例えば

    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> ...
        }
    };

メンバー関数ドキュメント

QSharedPointer<T> QEnableSharedFromThis::sharedFromThis()

this (つまり、このメソッドを呼び出しているサブクラスのインスタンス) がQSharedPointer によって管理されている場合は、this を指す共有ポインタのインスタンスを返し、そうでない場合は nullQSharedPointer を返す。

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

これはオーバーロードされた関数です。

sharedFromThis() の定数オーバーロード。

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.