QScopedPointer Class

template <typename T, typename Cleanup = QScopedPointerDeleter<T>> class QScopedPointer

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

Header: #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)
bool 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)라고 합니다.

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

이 함수는 수동 삭제 호출에 의해 방해받습니다. 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);
}

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

일반 C++ 포인터의 생성자 자격도 QScopedPointer로 표현할 수 있습니다:

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

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

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

커스텀 정리 핸들러

malloc 으로 할당된 포인터뿐만 아니라 배열도 delete 을 사용하여 삭제해서는 안 됩니다. QScopedPointer의 두 번째 템플릿 매개변수는 사용자 정의 정리 처리기에 사용할 수 있습니다.

다음과 같은 사용자 정의 정리 처리기가 있습니다:

  • 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 인 경우를 제외하고는 작동하지 않습니다.

[explicit] bool 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)

lhsrhs 이 서로 다른 포인터를 참조하는 경우 true 을 반환합니다.

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

lhs 이 유효한(즉, 널이 아닌) 포인터를 참조하는 경우 true 을 반환합니다.

QScopedPointer::isNull()도 참조하세요 .

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

rhs 이 유효한(즉, 널이 아닌) 포인터를 참조하는 경우 true 을 반환합니다.

QScopedPointer::isNull()도 참조하세요 .

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

lhsrhs 이 동일한 포인터를 참조하는 경우 true 을 반환합니다.

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

lhsnullptr 을 참조하는 경우 true 을 반환합니다.

QScopedPointer::isNull()도 참조하세요 .

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

rhsnullptr 을 참조하는 경우 true 을 반환합니다.

QScopedPointer::isNull()도 참조하세요 .

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