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_impl.h | 41 +++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) (limited to 'src/corelib/tools/qsharedpointer_impl.h') diff --git a/src/corelib/tools/qsharedpointer_impl.h b/src/corelib/tools/qsharedpointer_impl.h index 7dafa4981c..fe79aa1db1 100644 --- a/src/corelib/tools/qsharedpointer_impl.h +++ b/src/corelib/tools/qsharedpointer_impl.h @@ -91,6 +91,7 @@ template inline void qt_sharedpointer_cast_check(T *) { } // template class QWeakPointer; template class QSharedPointer; +template class QEnableSharedFromThis; class QVariant; @@ -479,6 +480,14 @@ private: delete d; } + template + inline void enableSharedFromThis(const QEnableSharedFromThis *ptr) + { + ptr->initializeFromSharedPointer(*this); + } + + inline void enableSharedFromThis(...) {} + template inline void internalConstruct(T *ptr, Deleter deleter) { @@ -499,6 +508,7 @@ private: internalSafetyCheckAdd(d, ptr); #endif d->setQObjectShared(ptr, true); + enableSharedFromThis(ptr); } template @@ -707,6 +717,37 @@ public: T *value; }; +template +class QEnableSharedFromThis +{ +protected: +#ifdef Q_COMPILER_DEFAULT_MEMBERS + QEnableSharedFromThis() = default; +#else + Q_DECL_CONSTEXPR QEnableSharedFromThis() {} +#endif + QEnableSharedFromThis(const QEnableSharedFromThis &) {} + QEnableSharedFromThis &operator=(const QEnableSharedFromThis &) { return *this; } + +public: + inline QSharedPointer sharedFromThis() { return QSharedPointer(weakPointer); } + inline QSharedPointer sharedFromThis() const { return QSharedPointer(weakPointer); } + +#ifndef Q_NO_TEMPLATE_FRIENDS +private: + template friend class QSharedPointer; +#else +public: +#endif + template + inline void initializeFromSharedPointer(const QSharedPointer &ptr) const + { + weakPointer = ptr; + } + + mutable QWeakPointer weakPointer; +}; + // // operator== and operator!= // -- cgit v1.2.3