考虑以下代码:
int counter = 0;
QTimer* timer = new QTimer(this);
connect(timer, &QTimer::timeout, [this, &counter]() mutable {
counter++;
qDebug() << counter;
});
timer->start(500);
预期:
1
2
3
4
...
输出:
32766 (a random number)
...
这里发生了一些未定义的事情吗?我找不到任何有关此效果的信息。
最佳答案
[]
中的
&counter
表示您正在 lambda 中通过引用捕获 counter
。
如果变量int counter
超出了范围(局部变量通常会这样做),那么这意味着您有一个悬空引用;使用它是未定义的行为。
解决此问题的简单方法是仅按值捕获计数器 - [this, counter]
而不是 [this, &counter]
。然后 lambda 将拥有自己的 counter
状态拷贝。由于它是可变的,因此它将有权编辑自己的状态。
关于c++ - Qt连接: Using Lambda Expression Resets Passed int Variable (Weird),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57295332/