Qt 4.8
Public Types | Public Functions | Protected Variables | Private Types | List of all members
QScopedPointer< T, Cleanup > Class Template Reference

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

#include <qscopedpointer.h>

Inheritance diagram for QScopedPointer< T, Cleanup >:
QCustomScopedPointer< T, Cleanup > QScopedArrayPointer< T, Cleanup >

Public Types

typedef T * pointer
 

Public Functions

T * data () const
 Returns the value of the pointer referenced by this object. More...
 
bool isNull () const
 Returns true if this object is holding a pointer that is null. More...
 
 operator bool () const
 Returns true if this object is not null. More...
 
bool operator! () const
 Returns true if the pointer referenced by this object is null, otherwise returns false. More...
 
T & operator* () const
 Provides access to the scoped pointer's object. More...
 
T * operator-> () const
 Provides access to the scoped pointer's object. More...
 
 QScopedPointer (T *p=0)
 Constructs this QScopedPointer instance and sets its pointer to p. More...
 
void reset (T *other=0)
 Deletes the existing object it is pointing to if any, and sets its pointer to other. More...
 
void swap (QScopedPointer< T, Cleanup > &other)
 Swap this pointer with other. More...
 
T * take ()
 Returns the value of the pointer referenced by this object. More...
 
 ~QScopedPointer ()
 Destroys this QScopedPointer object. More...
 

Protected Variables

T * d
 

Private Types

typedef T *QScopedPointer::* RestrictedBool
 

Detailed Description

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

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

Since
4.6
Note
This class or function is reentrant.

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. With QScopedPointer, the code can be simplified to:

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

The code the compiler generates for QScopedPointer is the same as when writing it manually. Code that makes use of delete are candidates for QScopedPointer usage (and if not, possibly another type of smart pointer such as QSharedPointer). 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 a QScopedPointer:

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

Custom cleanup handlers

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

The following custom cleanup handlers exist:

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

// this QScopedPointer deletes its data using the delete[] operator:
// 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:

Forward Declared Pointers

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

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

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 implicitely
// generate them.
};

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

See also
QSharedPointer

Definition at line 87 of file qscopedpointer.h.

Typedefs

◆ pointer

template<typename T, typename Cleanup = QScopedPointerDeleter<T>>
QScopedPointer< T, Cleanup >::pointer
Warning
This function is not part of the public interface.

Definition at line 164 of file qscopedpointer.h.

◆ RestrictedBool

template<typename T, typename Cleanup = QScopedPointerDeleter<T>>
typedef T* QScopedPointer::* QScopedPointer< T, Cleanup >::RestrictedBool
private

Definition at line 90 of file qscopedpointer.h.

Constructors and Destructors

◆ QScopedPointer()

template<typename T, typename Cleanup = QScopedPointerDeleter<T>>
QScopedPointer< T, Cleanup >::QScopedPointer ( T *  p = 0)
inlineexplicit

Constructs this QScopedPointer instance and sets its pointer to p.

Definition at line 93 of file qscopedpointer.h.

93  : d(p)
94  {
95  }

◆ ~QScopedPointer()

template<typename T, typename Cleanup = QScopedPointerDeleter<T>>
QScopedPointer< T, Cleanup >::~QScopedPointer ( )
inline

Destroys this QScopedPointer object.

Delete the object its pointer points to.

Definition at line 97 of file qscopedpointer.h.

98  {
99  T *oldD = this->d;
100  Cleanup::cleanup(oldD);
101  this->d = 0;
102  }
static void cleanup()
Definition: qpicture.cpp:1508

Functions

◆ data()

template<typename T, typename Cleanup = QScopedPointerDeleter<T>>
T * QScopedPointer< T, Cleanup >::data ( ) const
inline

Returns the value of the pointer referenced by this object.

QScopedPointer still owns the object pointed to.

Definition at line 133 of file qscopedpointer.h.

Referenced by QProcessPrivate::_q_notified(), QGraphicsScenePrivate::_q_polishItems(), QDirectFbInput::addWindow(), QDirectFbBlitter::alphaFillRect(), QRasterPaintEngine::alphaPenBlt(), QPainterPrivate::attachPainterPrivate(), QBlittablePixmapData::blittable(), QDomHandler::characters(), QGraphicsItemPrivate::childrenBoundingRectHelper(), QConfFileSettingsPrivate::clear(), QRasterPaintEngine::clip(), QStandardItemModelPrivate::columnsInserted(), QStandardItemModelPrivate::columnsRemoved(), QLibraryInfoPrivate::configuration(), convert_ARGB_PM_to_Indexed8(), convert_ARGB_PM_to_Mono(), convert_RGB_to_Indexed8(), QSoftKeyManager::createKeyedAction(), QDirectFbIntegration::createPlatformWindow(), QAdoptedThread::createThreadForAdoption(), QPainterPath::d_func(), QNetworkDiskCache::data(), QBrush::detach(), QDirectFbScreen::dfbLayer(), QDirectFbBlitter::dfbSurface(), QDirectFbWindow::dfbSurface(), QDirectFbConvenience::dfbSurfaceForPlatformPixmap(), QDirectFbWindow::dfbWindow(), dither_to_Mono(), QDirectFbBlitter::doLock(), QDirectFbBlitter::doUnlock(), QGraphicsScenePrivate::drawItemHelper(), QDirectFbBlitter::drawPixmapOpacity(), QRasterPaintEngine::drawPolygon(), QConfFileSettingsPrivate::fileName(), QVGPaintEngine::fill(), QOpenGLPaintEngine::fill(), QRasterPaintEngine::fill(), QRasterPaintEngine::fillPath(), QRasterPaintEngine::fillPolygon(), QGLEngineSharedShaders::findProgramInCache(), QDirectFbWindowSurface::flush(), QDirectFbIntegration::fontDatabase(), QFreetypeFace::getFace(), QDirectFbInput::globalPoint(), QBrush::gradient(), QDirectFbInput::handleEvents(), QDirectFbInput::handleMouseEvents(), QDirectFbIntegration::initializeInput(), QDirectFbIntegration::initializeScreen(), QSoftKeyManager::instance(), QGraphicsItemPrivate::invalidateChildGraphicsEffectsRecursively(), QGraphicsItemPrivate::invalidateParentGraphicsEffectsRecursively(), QConfFileSettingsPrivate::isWritable(), QGraphicsItem::itemTransform(), loadEngine(), loadSingleEngine(), QHostInfo::lookupHost(), QDirectFbWindow::lower(), QGraphicsViewPrivate::mapToViewRect(), QGraphicsItemPrivate::markParentDirty(), operator!=(), operator<<(), QNetworkAddressEntry::operator=(), QSslCipher::operator=(), QHostInfo::operator=(), QScriptValueProperty::operator=(), QScriptDebuggerValueProperty::operator=(), QScriptDebuggerConsoleCommandGroupData::operator=(), QScriptScriptData::operator=(), QScriptDebuggerValue::operator=(), QHostAddress::operator=(), QBrush::operator=(), QSslError::operator=(), QBrush::operator==(), operator==(), QDir::operator==(), operator>>(), QWidgetPrivate::paintBackground(), QDirectFbWindowSurface::paintDevice(), QBlittablePixmapData::paintEngine(), QGraphicsView::paintEvent(), QVGPaintEngine::pixmapFilter(), QThread::priority(), QGraphicsScenePrivate::processDirtyItemsRecursive(), QBrush::QBrush(), QDirectFbBlitter::QDirectFbBlitter(), QDirectFbScreen::QDirectFbScreen(), QDirectFbWindow::QDirectFbWindow(), QDirectFbWindowSurface::QDirectFbWindowSurface(), qHasPixmapTexture(), QSslCipher::QSslCipher(), QSslError::QSslError(), qt_closestItemFirst(), qt_closestLeaf(), QSignalEventGenerator::qt_metacall(), QZipReader::QZipReader(), QZipWriter::QZipWriter(), QDirectFbWindow::raise(), registerFont(), QDBusAdaptorConnector::relaySlot(), QConfFileSettingsPrivate::remove(), QDirectFbInput::removeWindow(), QDirectFbWindowSurface::resize(), QStandardItemModelPrivate::rowsInserted(), QStandardItemModelPrivate::rowsRemoved(), QDirectFbInput::run(), QGraphicsItem::sceneBoundingRect(), QGraphicsItemPrivate::sceneEffectiveBoundingRect(), QDirectFbWindowSurface::scroll(), QConfFileSettingsPrivate::set(), QBrush::setColor(), QDirectFbWindow::setGeometry(), QGraphicsWidget::setGeometry(), QGraphicsTransformPrivate::setItem(), QDirectFbWindow::setKeyboardGrabEnabled(), QDirectFbWindow::setMouseGrabEnabled(), QDirectFbWindow::setOpacity(), QBrush::setTexture(), QBrush::setTextureImage(), QDirectFbWindow::setVisible(), QDirectFbWindow::setWindowFlags(), QDirPrivate::sortFileList(), QTreeModel::sortItems(), QThreadPoolPrivate::startThread(), QDirectFbInput::stopInputEventLoop(), QConfFileSettingsPrivate::sync(), QConfFileSettingsPrivate::syncConfFile(), QBrush::texture(), QBrush::textureImage(), QGraphicsItemPrivate::updateChildWithGraphicsEffectFlagRecursively(), QDirectFbWindow::winId(), QDirectFbWindow::~QDirectFbWindow(), and QGraphicsItem::~QGraphicsItem().

134  {
135  return d;
136  }

◆ isNull()

template<typename T, typename Cleanup = QScopedPointerDeleter<T>>
bool QScopedPointer< T, Cleanup >::isNull ( ) const
inline

◆ operator bool()

template<typename T, typename Cleanup = QScopedPointerDeleter<T>>
QScopedPointer< T, Cleanup >::operator bool ( ) const
inline

Returns true if this object is not null.

This function is suitable for use in if-constructs, like:

if (scopedPointer) {
...
}
See also
isNull()

Definition at line 122 of file qscopedpointer.h.

123  {
124  return isNull() ? 0 : &QScopedPointer::d;
125  }
bool isNull() const
Returns true if this object is holding a pointer that is null.

◆ operator!()

template<typename T, typename Cleanup = QScopedPointerDeleter<T>>
bool QScopedPointer< T, Cleanup >::operator! ( ) const
inline

Returns true if the pointer referenced by this object is null, otherwise returns false.

See also
isNull()

Definition at line 116 of file qscopedpointer.h.

117  {
118  return !d;
119  }

◆ operator*()

template<typename T, typename Cleanup = QScopedPointerDeleter<T>>
T & QScopedPointer< T, Cleanup >::operator* ( ) const
inline

Provides access to the scoped pointer's object.

If the contained pointer is null, behavior is undefined.

See also
isNull()

Definition at line 104 of file qscopedpointer.h.

105  {
106  Q_ASSERT(d);
107  return *d;
108  }
#define Q_ASSERT(cond)
Definition: qglobal.h:1823

◆ operator->()

template<typename T, typename Cleanup = QScopedPointerDeleter<T>>
T * QScopedPointer< T, Cleanup >::operator-> ( ) const
inline

Provides access to the scoped pointer's object.

If the contained pointer is null, behavior is undefined.

See also
isNull()

Definition at line 110 of file qscopedpointer.h.

111  {
112  Q_ASSERT(d);
113  return d;
114  }
#define Q_ASSERT(cond)
Definition: qglobal.h:1823

◆ reset()

template<typename T, typename Cleanup = QScopedPointerDeleter<T>>
void QScopedPointer< T, Cleanup >::reset ( T *  other = 0)
inline

Deletes the existing object it is pointing to if any, and sets its pointer to other.

QScopedPointer now owns other and will delete it in its destructor.

Definition at line 143 of file qscopedpointer.h.

Referenced by QFSFileEngineIterator::advance(), QPainterPrivate::attachPainterPrivate(), QBlittablePixmapData::blittable(), QDomHandler::characters(), QLibraryInfoPrivate::cleanup(), QCompletionModel::createEngine(), QFileDialogPrivate::createWidgets(), QRuntimeGraphicsSystem::createWindowSurface(), QNetworkDiskCache::data(), QBrush::detach(), QPainterPath::detach_helper(), QPainterPrivate::detachPainterPrivate(), QPainterPath::ensureData_helper(), QBlittablePixmapData::fill(), QGLEngineSharedShaders::findProgramInCache(), QRuntimeWindowSurface::flush(), QFSFileEngineIterator::hasNext(), QDirPrivate::initFileEngine(), QDirectFbIntegration::initializeDirectFB(), QDirectFbIntegration::initializeInput(), QDirectFbIntegration::initializeScreen(), QSoftKeyManager::instance(), loadEngine(), loadSingleEngine(), QDir::makeAbsolute(), QPrinterInfo::operator=(), QScriptValueIterator::operator=(), QBrush::operator=(), QPainterPath::operator=(), operator>>(), QBlittablePixmapData::paintEngine(), QRegExpEngine::parse(), QVGPaintEngine::pixmapFilter(), QNetworkDiskCache::prepare(), QBrush::QBrush(), QConfFileSettingsPrivate::QConfFileSettingsPrivate(), QDirectFBCursor::QDirectFBCursor(), QDirectFbScreen::QDirectFbScreen(), QDirectFbWindowSurface::QDirectFbWindowSurface(), QDirIteratorPrivate::QDirIteratorPrivate(), QTest::qExec(), QPainter::QPainter(), QPrinterInfo::QPrinterInfo(), QScriptDebuggerValue::QScriptDebuggerValue(), QScriptValueIterator::QScriptValueIterator(), QTreeWidgetItemIterator::QTreeWidgetItemIterator(), QXmlSimpleReaderPrivate::QXmlSimpleReaderPrivate(), registerFont(), QSettings::registerFormat(), QBlittablePixmapData::resize(), QBlittablePixmapData::setBlittable(), QDataStream::setFloatingPointPrecision(), QRuntimeGraphicsSystem::setGraphicsSystem(), and QRegExpEngine::startTokenizer().

144  {
145  if (d == other)
146  return;
147  T *oldD = d;
148  d = other;
149  Cleanup::cleanup(oldD);
150  }
static void cleanup()
Definition: qpicture.cpp:1508

◆ swap()

template<typename T, typename Cleanup = QScopedPointerDeleter<T>>
void QScopedPointer< T, Cleanup >::swap ( QScopedPointer< T, Cleanup > &  other)
inline

Swap this pointer with other.

Definition at line 159 of file qscopedpointer.h.

Referenced by qSwap().

160  {
161  qSwap(d, other.d);
162  }
Q_INLINE_TEMPLATE void qSwap(QScopedPointer< T, Cleanup > &p1, QScopedPointer< T, Cleanup > &p2)

◆ take()

template<typename T, typename Cleanup = QScopedPointerDeleter<T>>
T * QScopedPointer< T, Cleanup >::take ( )
inline

Properties

◆ d

template<typename T, typename Cleanup = QScopedPointerDeleter<T>>
T* QScopedPointer< T, Cleanup >::d
protected

The documentation for this class was generated from the following files: