2

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.

2
  • 4
    You capture a reference to a local variable. Once that local variable dies (because you leave the scope it was defined in) you have a dangling reference. Commented Jul 31, 2019 at 16:36
  • That was the solution! After making "counter" into a class member variable, it never died, and no more dangling reference. Thanks! Commented Jul 31, 2019 at 16:42

1 Answer 1

4

&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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.