是否有可能断开lambda函数? 如果“是”,怎么样?
据https://qt-project.org/wiki/New_Signal_Slot_Syntax我需要使用QMetaObject::Connection
是从QObject的返回::连接方法,但我怎么能传递对象lambda函数?
伪代码示例:
QMetaObject::Connection conn = QObject::connect(m_sock, &QLocalSocket::readyRead, [this](){
QObject::disconnect(conn); //<---- Won't work because conn isn't captured
//do some stuff with sock, like sock->readAll();
}
如果捕获conn
直接,你捕获通过复制一个未初始化的对象,这会导致不确定的行为。 您需要捕获一个智能指针:
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);
// ...
}
或使用共享指针,与稍大的开销:
auto conn = std::make_shared<QMetaObject::Connection>();
*conn = QObject::connect(m_sock, &QLocalSocket::readyRead, [this, conn](){
QObject::disconnect(*conn);
// ...
}
从Qt的5.2你也可以使用一个上下文对象:
std::unique_ptr<QObject> context{new QObject};
QObject* pcontext = context.get();
QObject::connect(m_sock, &QLocalSocket::readyRead, pcontext,
[this, context = std::move(context)]() mutable {
context.clear();
// ...
});