Unsolved SingleShot-connection: will I get memory leaks like this?
-
Hey guys,
I've implemented a single-shot connection with timeout and I'm not completely sure if I will run into memory leaks.
//weak-connect to a functor with timeout template <typename Func1, typename Func2, typename Func3> static inline typename QtPrivate::QEnableIf<QtPrivate::FunctionPointer<Func2>::ArgumentCount == -1, QMetaObject::Connection>::Type weakConnect(const typename QtPrivate::FunctionPointer<Func1>::Object *sender, Func1 signal, Func2 slot, uint timeout, Func3 timeoutSlot) { QMetaObject::Connection conn_normal = QObject::connect(sender, signal, sender, slot, Qt::DirectConnection); QMetaObject::Connection* conn_delete = new QMetaObject::Connection(); QTimer* timer = NULL; *conn_delete = QObject::connect(sender, signal, [conn_normal, conn_delete](){ if (timer) { timer->stop(); timer->deleteLater(); } QObject::disconnect(conn_normal); QObject::disconnect(*conn_delete); delete conn_delete; }); if (timeout > 0) { timer = new QTimer; timer->setSingleShot(true); timer->setInterval(timeout); QObject::connect(timer, &QTimer::timeout, [conn_normal, conn_delete, timer, timeoutSlot] () { QObject::disconnect(conn_normal); QObject::disconnect(*conn_delete); delete conn_delete; timer->deleteLater(); timeoutSlot(); }); timer->start(); } return conn_normal; }
you can call it like that
weakConnect(engine, &Engine::positionReached, [&](bool reached) { ///fired if signal is emitted within 1000ms }, 1000, [&] { //fired if signal is NOT emitted within 1000ms });
The idea was to have a simple single-use connection with lamda-expressions.
I'm not completely sure if I will run into memory-leaks?
deleteLater() needs an eventloop. What if it's called outside an event-loop? Could I delete the timer the timeout-slot by delete(timer)? -
@themts said in SingleShot-connection: will I get memory leaks like this?:
deleteLater() needs an eventloop. What if it's called outside an event-loop? Could I delete the timer the timeout-slot by delete(timer)?
Yes, you could (I don't see why necessarily using a deleteLater here). Save that it looks good to me.