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

QEnableSharedFromThis 定义了两个名为sharedFromThis() 的成员函数,根据常量的不同,分别返回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() 的常量重载。

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