cid
cid

Reputation: 467

Qt Connections: Using Lambda Expression Resets Passed int Variable (Weird)

Consider the following code:

int counter = 0;

QTimer* timer = new QTimer(this);

connect(timer, &QTimer::timeout, [this, &counter]() mutable {
    counter++;
    qDebug() << counter;
});

timer->start(500);

Expected:

1
2
3
4
...

Output:

32766 (a random number)
...

Is there some undefined stuff going on here? I can't find anything about this effect.

Upvotes: 2

Views: 148

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275760

&counter in the [] means you are capturing counter by-reference in the lambda.

If the variable int counter has gone out of scope (as local variables are wont to do), then this means you have a dangling reference; using it is undefined behavior.

The easy way to fix this is to just capture counter by value -- [this, counter] instead of [this, &counter]. Then the lambda will own its own copy of the state of counter. As it is mutable, it will have permission to edit its own state.

Upvotes: 4

Related Questions