Friday, 15 January 2010

c++ - Disconnecting lambda functions in Qt5 -



c++ - Disconnecting lambda functions in Qt5 -

is possible disconnect lambda function? , if "yes", how?

according https://qt-project.org/wiki/new_signal_slot_syntax need utilize qmetaobject::connection returned qobject::connect method, how can pass object lambda function?

pseudo-code example:

qmetaobject::connection conn = qobject::connect(m_sock, &qlocalsocket::readyread, [this](){ qobject::disconnect(conn); //<---- won't work because conn isn't captured //do stuff sock, sock->readall(); }

if capture conn directly, you're capturing uninitialised object copy, results in undefined behaviour. need capture smart pointer:

std::unique_ptr<qmetaobject::connection> pconn{new qmetaobject::connection}; qmetaobject::connection &conn = *pconn; conn = qobject::connect(m_sock, &qlocalsocket::readyread, [this, pconn, &conn](){ qobject::disconnect(conn); // ... }

or using shared pointer, greater overhead:

auto conn = std::make_shared<qmetaobject::connection>(); *conn = qobject::connect(m_sock, &qlocalsocket::readyread, [this, conn](){ qobject::disconnect(*conn); // ... }

c++ lambda qt5

No comments:

Post a Comment