이 페이지에서

QScopedPointer Class

template <typename T, typename Cleanup> class QScopedPointer

QScopedPointer 클래스는 동적으로 할당된 객체에 대한 포인터를 저장하며, 소멸 시 해당 객체를 삭제합니다. 더 보기...

헤더: #include <QScopedPointer>
CMake: find_package(Qt6 REQUIRED COMPONENTS Core)
target_link_libraries(mytarget PRIVATE Qt6::Core)
qmake: QT += core
상속됨:

QScopedArrayPointer

참고: 이 클래스의 모든 함수는 재진입 가능합니다.

공개 함수

QScopedPointer(T *p = nullptr)
~QScopedPointer()
T *data() const
T *get() const
bool isNull() const
void reset(T *other = nullptr)
operator bool() const
bool operator!() const
T &operator*() const
T *operator->() const
bool operator!=(const QScopedPointer<T, Cleanup> &lhs, const QScopedPointer<T, Cleanup> &rhs)
bool operator!=(const QScopedPointer<T, Cleanup> &lhs, std::nullptr_t)
bool operator!=(std::nullptr_t, const QScopedPointer<T, Cleanup> &rhs)
bool operator==(const QScopedPointer<T, Cleanup> &lhs, const QScopedPointer<T, Cleanup> &rhs)
bool operator==(const QScopedPointer<T, Cleanup> &lhs, std::nullptr_t)
bool operator==(std::nullptr_t, const QScopedPointer<T, Cleanup> &rhs)

자세한 설명

힙에 할당된 객체를 수동으로 관리하는 것은 어렵고 오류가 발생하기 쉬우며, 그 결과 코드가 메모리 누수를 일으키고 유지 관리가 어려워지는 경우가 많습니다. QScopedPointer는 힙 할당에 스택 기반 메모리 소유권을 할당함으로써 이 과정을 대폭 단순화하는 작은 유틸리티 클래스로, 더 일반적으로 RAII(리소스 획득은 초기화)라고 불립니다. 템플릿 매개변수 T 는 관리되는 포인터의 유형을 지정합니다.

QScopedPointer는 현재 스코프가 사라지면 포인터가 가리키는 객체가 삭제되도록 보장합니다.

힙 할당을 수행하고 여러 종료 지점을 가진 다음 함수를 살펴보겠습니다:

void myFunction(bool useSubClass)
{
    MyClass *p = useSubClass ? new MyClass() : new MySubClass;
    QIODevice *device = handsOverOwnership();

    if (m_value > 3) {
        delete p;
        delete device;
        return;
    }

    try {
        process(device);
    }
    catch (...) {
        delete p;
        delete device;
        throw;
    }

    delete p;
    delete device;
}

이 코드는 수동으로 delete 호출을 해야 한다는 점에서 번거롭습니다. QScopedPointer를 사용하면 코드를 다음과 같이 단순화할 수 있습니다:

void myFunction(bool useSubClass)
{
    // assuming that MyClass has a virtual destructor
    QScopedPointer<MyClass> p(useSubClass ? new MyClass() : new MySubClass);
    QScopedPointer<QIODevice> device(handsOverOwnership());

    if (m_value > 3)
        return;

    process(device.data());
}

컴파일러가 QScopedPointer를 위해 생성하는 코드는 수동으로 작성했을 때와 동일합니다. ` delete `를 사용하는 코드는 QScopedPointer를 사용할 수 있는 후보입니다(그렇지 않다면 ` QSharedPointer`와 같은 다른 유형의 스마트 포인터를 사용할 수 있습니다). QScopedPointer는 소유권과 수명을 명확하게 전달하기 위해 의도적으로 복사 생성자나 할당 연산자를 제공하지 않습니다.

일반 C++ 포인터에 적용되는 const 한정자는 QScopedPointer로도 표현할 수 있습니다:

    const QWidget *const p = new QWidget();
    // is equivalent to:
    const QScopedPointer<const QWidget> p1(new QWidget());

    QWidget *const p = new QWidget();
    // is equivalent to:
    const QScopedPointer<QWidget> p1(new QWidget());

    const QWidget *p = new QWidget();
    // is equivalent to:
    QScopedPointer<const QWidget> p1(new QWidget());

사용자 정의 정리 핸들러

malloc 로 할당된 포인터와 배열은 delete 를 사용하여 삭제해서는 안 됩니다. Cleanup 템플릿 매개변수는 스코프 포인터가 소멸될 때 사용할 정리 핸들러를 지정하며, 기본적으로는 QScopedPointerDeleter가 사용됩니다.

다음과 같은 사용자 정의 정리 핸들러가 있습니다:

  • QScopedPointerDeleter - 기본값으로, 다음을 사용하여 포인터를 삭제합니다. delete
  • QScopedPointerArrayDeleter - delete [] 를 사용하여 포인터를 삭제합니다. new [] 로 할당된 포인터에는 이 핸들러를 사용하십시오.
  • QScopedPointerPodDeleter - ` free()`를 사용하여 포인터를 삭제합니다. ` malloc()`로 할당된 포인터에 이 핸들러를 사용하십시오.
  • QScopedPointerDeleteLater - deleteLater() 를 호출하여 포인터를 삭제합니다. QEventLoop 에 적극적으로 참여하고 있는 QObject 객체를 가리키는 포인터에 이 핸들러를 사용하십시오.

void cleanup(T *pointer) 라는 공용 정적 함수가 있는 경우, 사용자 정의 클래스를 핸들러로 전달할 수 있습니다.

// this QScopedPointer deletes its data using the delete[] operator:
QScopedPointer<int, QScopedPointerArrayDeleter<int> > arrayPointer(new int[42]);

// this QScopedPointer frees its data using free():
QScopedPointer<int, QScopedPointerPodDeleter> podPointer(reinterpret_cast<int *>(malloc(42)));

// this struct calls "myCustomDeallocator" to delete the pointer
struct ScopedPointerCustomDeleter
{
    static inline void cleanup(MyCustomClass *pointer)
    {
        myCustomDeallocator(pointer);
    }
};

// QScopedPointer using a custom deleter:
QScopedPointer<MyCustomClass, ScopedPointerCustomDeleter> customPointer(new MyCustomClass);

사전 선언된 포인터

선 선언된 클래스는 QScopedPointer가 정리 작업을 수행해야 할 때마다 해당 선 선언된 클래스의 소멸자가 사용 가능하기만 하면 QScopedPointer 내에서 사용할 수 있습니다.

구체적으로 말하면, 선선언된 클래스를 가리키는 QScopedPointer를 포함하는 모든 클래스는 비인라인 생성자, 소멸자 및 할당 연산자를 가져야 합니다:

class MyPrivateClass; // forward declare MyPrivateClass

class MyClass
{
private:
    QScopedPointer<MyPrivateClass> privatePtr; // QScopedPointer to forward declared class

public:
    MyClass(); // OK
    inline ~MyClass() {} // VIOLATION - Destructor must not be inline

private:
    Q_DISABLE_COPY(MyClass) // OK - copy constructor and assignment operators
                            // are now disabled, so the compiler won't implicitly
                            // generate them.
};

그렇지 않으면 컴파일러는 MyPrivateClass 를 소멸할 수 없다는 경고 메시지를 출력합니다.

QSharedPointer도 참조하십시오 .

멤버 함수 문서

[explicit noexcept] QScopedPointer::QScopedPointer(T *p = nullptr)

이 QScopedPointer 인스턴스를 생성하고, 해당 포인터를 p 로 설정합니다.

QScopedPointer::~QScopedPointer()

이 QScopedPointer 객체를 파기합니다. 해당 포인터가 가리키는 객체를 삭제합니다.

[noexcept] T *QScopedPointer::data() const

이 객체가 참조하는 포인터의 값을 반환합니다. ` QScopedPointer `는 여전히 해당 포인터가 가리키는 객체를 소유하고 있습니다.

[noexcept] T *QScopedPointer::get() const

data()와 동일합니다.

[noexcept] bool QScopedPointer::isNull() const

이 객체가 ` nullptr`을 가리키는 경우 ` true `을 반환합니다.

[noexcept(...)] void QScopedPointer::reset(T *other = nullptr)

이 함수는 포인터가 가리키는 기존 객체(있는 경우)를 삭제하고, 포인터를 ` other`로 설정합니다. ` QScopedPointer `는 이제 ` other `를 소유하게 되며, 소멸자에서 이를 삭제합니다.

참고: noexcept(Cleanup::cleanup(std::declval<T *>())) 가 true 인 경우,이 함수는 noexcept입니다.

[explicit] QScopedPointer::operator bool() const

포함된 포인터가 ` nullptr`가 아닌 경우 ` true `를 반환합니다. 이 함수는 다음과 같이 ` if-constructs`에서 사용하기에 적합합니다:

if (scopedPointer) {
    //...
}

isNull()도 참조하십시오 .

[noexcept] bool QScopedPointer::operator!() const

이 객체가 nullptr 를 가리키는 경우 true 를 반환합니다.

isNull()도 참조하십시오 .

T &QScopedPointer::operator*() const

범위가 지정된 포인터가 가리키는 객체에 대한 액세스를 제공합니다.

포함된 포인터가 ` nullptr`인 경우, 동작은 정의되지 않습니다.

isNull()도 참조하십시오 .

[noexcept] T *QScopedPointer::operator->() const

범위가 지정된 포인터가 가리키는 객체에 대한 액세스를 제공합니다.

포함된 포인터가 ` nullptr`인 경우, 동작은 정의되지 않습니다.

isNull()도 참조하십시오 .

관련 비회원 함수

[noexcept] bool operator!=(const QScopedPointer<T, Cleanup> &lhs, const QScopedPointer<T, Cleanup> &rhs)

lhs 와 rhs 가 서로 다른 포인터를 가리키는 경우, true 를 반환합니다.

[noexcept] bool operator!=(const QScopedPointer<T, Cleanup> &lhs, std::nullptr_t)

lhs 가 유효한(즉, null이 아닌) 포인터를 가리키는 경우 true 를 반환합니다.

QScopedPointer::isNull()도 참조하십시오 .

[noexcept] bool operator!=(std::nullptr_t, const QScopedPointer<T, Cleanup> &rhs)

rhs 가 유효한(즉, null이 아닌) 포인터를 가리키는 경우 true 를 반환합니다.

QScopedPointer::isNull()도 참조하십시오 .

[noexcept] bool operator==(const QScopedPointer<T, Cleanup> &lhs, const QScopedPointer<T, Cleanup> &rhs)

lhs 와 rhs 가 동일한 포인터를 가리키는 경우 true 를 반환합니다.

[noexcept] bool operator==(const QScopedPointer<T, Cleanup> &lhs, std::nullptr_t)

lhs 가 nullptr 를 가리키는 경우 true 를 반환합니다.

QScopedPointer::isNull()도 참조하십시오 .

[noexcept] bool operator==(std::nullptr_t, const QScopedPointer<T, Cleanup> &rhs)

rhs 가 nullptr 를 가리키는 경우 true 를 반환합니다.

QScopedPointer::isNull()도 참조하십시오 .

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