在QT5断开的lambda函数(Disconnecting lambda functions in

2019-07-19 18:28发布

是否有可能断开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();
}

Answer 1:

如果捕获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();
        // ...
    });


文章来源: Disconnecting lambda functions in Qt5
标签: c++ lambda qt5