Movatterモバイル変換


[0]ホーム

URL:


We bake cookies in your browser for a better experience. Using this site means that you consent.Read More

Menu

Qt Documentation

QScopedPointer Class

TheQScopedPointer class stores a pointer to a dynamically allocated object, and deletes it upon destruction.More...

Header:#include <QScopedPointer>
Since: Qt 4.6
Inherited By:

QScopedArrayPointer

Note: All functions in this class arereentrant.

Public Functions

QScopedPointer(T * p = 0)
~QScopedPointer()
T *data() const
boolisNull() const
voidreset(T * other = 0)
voidswap(QScopedPointer<T, Cleanup> & other)
T *take()
operator bool() const
booloperator!() const
T &operator*() const
T *operator->() const

Detailed Description

TheQScopedPointer class stores a pointer to a dynamically allocated object, and deletes it upon destruction.

Managing heap allocated objects manually is hard and error prone, with the common result that code leaks memory and is hard to maintain.QScopedPointer is a small utility class that heavily simplifies this by assigning stack-based memory ownership to heap allocations, more generally called resource acquisition is initialization(RAII).

QScopedPointer guarantees that the object pointed to will get deleted when the current scope disappears.

Consider this function which does heap allocations, and have various exit points:

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

It's encumbered by the manual delete calls. WithQScopedPointer, the code can be simplified to:

void myFunction(bool useSubClass){// assuming that MyClass has a virtual destructorQScopedPointer<MyClass> p(useSubClass?new MyClass() :new MySubClass);QScopedPointer<QIODevice> device(handsOverOwnership());if (m_value>3)return;    process(device);}

The code the compiler generates forQScopedPointer is the same as when writing it manually. Code that makes use ofdelete are candidates forQScopedPointer usage (and if not, possibly another type of smart pointer such asQSharedPointer).QScopedPointer intentionally has no copy constructor or assignment operator, such that ownership and lifetime is clearly communicated.

The const qualification on a regular C++ pointer can also be expressed with aQScopedPointer:

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

Custom cleanup handlers

Arrays as well as pointers that have been allocated withmalloc must not be deleted usingdelete.QScopedPointer's second template parameter can be used for custom cleanup handlers.

The following custom cleanup handlers exist:

  • QScopedPointerDeleter - the default, deletes the pointer usingdelete
  • QScopedPointerArrayDeleter - deletes the pointer usingdelete []. Use this handler for pointers that were allocated withnew [].
  • QScopedPointerPodDeleter - deletes the pointer usingfree(). Use this handler for pointers that were allocated withmalloc().

You can pass your own classes as handlers, provided that they have a public static functionvoid cleanup(T *pointer).

// this QScopedPointer deletes its data using the delete[] operator:QScopedPointer<int,QScopedPointerArrayDeleter<int>> arrayPointer(newint[42]);// this QScopedPointer frees its data using free():QScopedPointer<int,QScopedPointerPodDeleter> podPointer(reinterpret_cast<int*>(malloc(42)));// this struct calls "myCustomDeallocator" to delete the pointerstruct ScopedPointerCustomDeleter{staticinlinevoid cleanup(MyCustomClass*pointer)    {        myCustomDeallocator(pointer);    }};// QScopedPointer using a custom deleter:QScopedPointer<MyCustomClass, ScopedPointerCustomDeleter> customPointer(new MyCustomClass);

Forward Declared Pointers

Classes that are forward declared can be used withinQScopedPointer, as long as the destructor of the forward declared class is available whenever aQScopedPointer needs to clean up.

Concretely, this means that all classes containing aQScopedPointer that points to a forward declared class must have non-inline constructors, destructors and assignment operators:

class MyPrivateClass;// forward declare MyPrivateClassclass MyClass{private:QScopedPointer<MyPrivateClass> privatePtr;// QScopedPointer to forward declared classpublic:    MyClass();// OKinline~MyClass() {}// VIOLATION - Destructor must not be inlineprivate:    Q_DISABLE_COPY(MyClass)// OK - copy constructor and assignment operators// are now disabled, so the compiler won't implicitely// generate them.};

Otherwise, the compiler output a warning about not being able to destructMyPrivateClass.

See alsoQSharedPointer.

Member Function Documentation

QScopedPointer::QScopedPointer(T * p = 0)

Constructs thisQScopedPointer instance and sets its pointer top.

QScopedPointer::~QScopedPointer()

Destroys thisQScopedPointer object. Delete the object its pointer points to.

T * QScopedPointer::data() const

Returns the value of the pointer referenced by this object.QScopedPointer still owns the object pointed to.

bool QScopedPointer::isNull() const

Returnstrue if this object is holding a pointer that isnull.

void QScopedPointer::reset(T * other = 0)

Deletes the existing object it is pointing to if any, and sets its pointer toother.QScopedPointer now ownsother and will delete it in its destructor.

void QScopedPointer::swap(QScopedPointer<T,Cleanup> & other)

Swap this pointer withother.

T * QScopedPointer::take()

Returns the value of the pointer referenced by this object. The pointer of thisQScopedPointer object will be reset tonull.

Callers of this function take ownership of the pointer.

QScopedPointer::operator bool() const

Returnstrue if this object is notnull. This function is suitable for use inif-constructs, like:

if (scopedPointer) {...}

See alsoisNull().

bool QScopedPointer::operator!() const

Returnstrue if the pointer referenced by this object isnull, otherwise returnsfalse.

See alsoisNull().

T & QScopedPointer::operator*() const

Provides access to the scoped pointer's object.

If the contained pointer isnull, behavior is undefined.

See alsoisNull().

T * QScopedPointer::operator->() const

Provides access to the scoped pointer's object.

If the contained pointer isnull, behavior is undefined.

See alsoisNull().

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


[8]ページ先頭

©2009-2025 Movatter.jp