From 03bcadc3e85e68cd870bc3395b1e65794214175a Mon Sep 17 00:00:00 2001 From: Kitsune Ral Date: Mon, 16 Apr 2018 13:40:23 +0900 Subject: ConnectionsGuard<> template to automatically disconnect subscribers Case in point is a room list model (so far in Quaternion, but planned for inclusion to the lib) that stores lists of connections and rooms; upon dropping, e.g., a room from the list the model should disconnect from the room's signals. --- lib/util.h | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/lib/util.h b/lib/util.h index 92198b0b..7ab1e20d 100644 --- a/lib/util.h +++ b/lib/util.h @@ -20,6 +20,7 @@ #include #include +#include #include #include @@ -41,6 +42,7 @@ namespace QMatrixClient } #endif + /** static_cast<> for unique_ptr's */ template inline auto unique_ptr_cast(PtrT2&& p) { @@ -55,5 +57,31 @@ namespace QMatrixClient template static void qAsConst(const T &&) Q_DECL_EQ_DELETE; #endif + + /** A guard pointer that disconnects an interested object upon destruction + * It's almost QPointer<> except that you have to initialise it with one + * more additional parameter - a pointer to a QObject that will be + * disconnected from signals of the underlying pointer upon the guard's + * destruction. + */ + template + class ConnectionsGuard : public QPointer + { + public: + ConnectionsGuard(T* publisher, QObject* subscriber) + : QPointer(publisher), subscriber(subscriber) + { } + ~ConnectionsGuard() + { + if (*this) + (*this)->disconnect(subscriber); + } + ConnectionsGuard(ConnectionsGuard&&) noexcept = default; + ConnectionsGuard& operator=(ConnectionsGuard&&) noexcept = default; + using QPointer::operator=; + + private: + QObject* subscriber; + }; } // namespace QMatrixClient -- cgit v1.2.3