이 페이지에서

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()이라는 두 개의 멤버 함수를 정의하며, 이 함수들은 const 여부에 따라 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 를 가리키는 공유 포인터 인스턴스를 반환하고, 그렇지 않은 경우 null 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.