本页内容

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 时,可以继承此类。 模板参数T 指定了从QEnableSharedFromThis继承的类的类型。关键点在于,不能仅通过返回QSharedPointer<T>(this)来实现,因为这最终会导致创建多个具有独立引用计数的QSharedPointer 对象。因此,绝不能从同一个原始指针创建多个QSharedPointer 。

QEnableSharedFromThis 定义了两个名为sharedFromThis() 的成员函数,它们根据常量性(constness)分别返回QSharedPointer<T> 和QSharedPointer<const T>,以供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
    }

也可以从类本身之外的对象获取共享指针。这在为脚本提供接口的代码中特别有用,因为目前脚本中尚无法使用共享指针。例如:

    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` 的共享指针实例;否则返回一个空的 `QSharedPointer`。

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

sharedFromThis() 的常量重载。

这是一个重载函数。

© 2026 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.