aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorKitsune Ral <Kitsune-Ral@users.sf.net>2018-04-16 13:40:23 +0900
committerKitsune Ral <Kitsune-Ral@users.sf.net>2018-04-16 13:40:23 +0900
commit03bcadc3e85e68cd870bc3395b1e65794214175a (patch)
tree5fb60ff6fd9063fef7532279074f3e5115fdd871
parent139a6743a4e7a3b2e380d4f3e8f43558bc3164fa (diff)
downloadlibquotient-03bcadc3e85e68cd870bc3395b1e65794214175a.tar.gz
libquotient-03bcadc3e85e68cd870bc3395b1e65794214175a.zip
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.
-rw-r--r--lib/util.h28
1 files changed, 28 insertions, 0 deletions
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 <QtCore/QMetaEnum>
#include <QtCore/QDebug>
+#include <QtCore/QPointer>
#include <functional>
#include <memory>
@@ -41,6 +42,7 @@ namespace QMatrixClient
}
#endif
+ /** static_cast<> for unique_ptr's */
template <typename T1, typename PtrT2>
inline auto unique_ptr_cast(PtrT2&& p)
{
@@ -55,5 +57,31 @@ namespace QMatrixClient
template <typename T>
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 <typename T>
+ class ConnectionsGuard : public QPointer<T>
+ {
+ public:
+ ConnectionsGuard(T* publisher, QObject* subscriber)
+ : QPointer<T>(publisher), subscriber(subscriber)
+ { }
+ ~ConnectionsGuard()
+ {
+ if (*this)
+ (*this)->disconnect(subscriber);
+ }
+ ConnectionsGuard(ConnectionsGuard&&) noexcept = default;
+ ConnectionsGuard& operator=(ConnectionsGuard&&) noexcept = default;
+ using QPointer<T>::operator=;
+
+ private:
+ QObject* subscriber;
+ };
} // namespace QMatrixClient