From 90a68926f311ac5bb8f7c53ac8370f9ff7f12c08 Mon Sep 17 00:00:00 2001 From: Roman Pasechnik Date: Tue, 2 Jul 2013 21:35:21 +0300 Subject: Add QEnableSharedFromThis class It enables you to get a valid QSharedPointer instance to 'this', when all you have is 'this'. Task-number: QTBUG-7287 Change-Id: I3ed1c9c4d6b110fe02302312cc3c4a75e9d95a0c Reviewed-by: Richard J. Moore --- src/corelib/tools/qsharedpointer.cpp | 54 ++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) (limited to 'src/corelib/tools/qsharedpointer.cpp') diff --git a/src/corelib/tools/qsharedpointer.cpp b/src/corelib/tools/qsharedpointer.cpp index 58a9a021d0..180f45eb56 100644 --- a/src/corelib/tools/qsharedpointer.cpp +++ b/src/corelib/tools/qsharedpointer.cpp @@ -371,6 +371,43 @@ \sa QSharedPointer, QScopedPointer */ +/*! + \class QEnableSharedFromThis + \inmodule QtCore + \brief A base class that allows to obtain a QSharedPointer for an object already managed by a shared pointer + \since 5.4 + + You can inherit this class when you need to create a QSharedPointer + from any instance of a class -- for instance, from within the + object itself. The key point is that the "obvious" technique of + just returning QSharedPointer(this) can not be used, because + this winds up creating multiple distinct QSharedPointer objects + with separate reference counts. For this reason you must never + create more than one QSharedPointer from the same raw pointer. + + QEnableSharedFromThis defines two member functions called + sharedFromThis() that return a QSharedPointer and + QSharedPointer, depending on constness, to \c this: + + \code + class Y: public QEnableSharedFromThis + { + public: + QSharedPointer f() + { + return sharedFromThis(); + } + }; + + int main() + { + QSharedPointer p(new Y()); + QSharedPointer y = p->f(); + Q_ASSERT(p == y); // p and q must share ownership + } + \endcode +*/ + /*! \fn QSharedPointer::QSharedPointer() @@ -923,6 +960,23 @@ may have had to the pointer. */ +/*! + \fn QSharedPointer QEnableSharedFromThis::sharedFromThis() + \since 5.4 + + If \c this (that is, the subclass instance invoking this method) is being + managed by a QSharedPointer, returns a shared pointer instance pointing to + \c this; otherwise returns a QSharedPointer holding a null pointer. +*/ + +/*! + \fn QSharedPointer QEnableSharedFromThis::sharedFromThis() const + \overload + \since 5.4 + + Const overload of sharedFromThis(). +*/ + /*! \fn bool operator==(const QSharedPointer &ptr1, const QSharedPointer &ptr2) \relates QSharedPointer -- cgit v1.2.3