alexandernst
alexandernst

Reputation: 15099

Qt5, lambda and scope of vars

I have a QLocalServer in Qt5, which is connected to the newConnection() signal.

That signal calls this function:

QLocalSocket *clientConnection = m_server->nextPendingConnection();
clientID++; // <--- declared in header
clientConnection->setProperty("ID", QVariant(clientID));

connect(clientConnection, &QLocalSocket::disconnected, [clientConnection](){
    qDebug() << "Client disconnected " << clientConnection->property("ID");
    clientConnection->deleteLater();
});

If two clients (client ID 1 and client ID 2) connect one after other, and then client 1 disconnects, what will happen inside the lambda function? I mean, after the second client has connected, what will happen with the value of clientConnection? Will it get overriden (so the clientConnection of the first client won't be valid anymore) or will each have valid data?

Upvotes: 1

Views: 217

Answers (1)

ecatmur
ecatmur

Reputation: 157414

Each instance of a lambda closure type has its own storage for members captured by value.

int i = 1;
auto l1 = [i]() { return i; };    // captures 1
i = 2;
auto l2 = [i]() { return i; };    // captures 2
l1();    // returns 1
l2();    // returns 2

Upvotes: 4

Related Questions