【发布时间】:2020-08-11 10:34:06
【问题描述】:
令我惊讶的是,下面的 C++ 程序:
#include <iostream>
#include <functional>
int main() {
std::function<void(void)> f;
{
int x = 1;
f = [&x]() { std::cout << x; };
}
//std::cout << x; // error: use of undeclared identifier 'x'
f(); // no error!
return 0;
}
输出:
1
我希望得到的输出与取消注释注释行时得到的输出相同:
error: use of undeclared identifier 'x'
因为 lambda f 捕获了自动变量 x 通过引用(不是 通过值)并且 x 在调用点不在上下文中f()(所以 x 中的 f body 是一个悬空引用)。
为什么通过引用捕获的 lambda 仍然适用于悬空引用?
【问题讨论】:
-
这是未定义的行为,你很幸运得到了你所做的输出,而且它似乎正在工作,不同的编译器/不同的优化或编译器标志可能会破坏它。
-
为什么在没有任何 lambdas 的情况下悬空引用起作用?
标签: c++ lambda scope reference name-binding