考虑一下:
#include <iostream>
#include <functional>
std::function<void()> task;
int x = 42;
struct Foo
{
int& x;
void bar()
{
task = [=]() { std::cout << x << '\n'; };
}
};
int main()
{
{
Foo f{x};
f.bar();
}
task();
}
Run Code Online (Sandbox Code Playgroud)
我的直觉是,当执行任务时,实际的指示对象仍然存在,我们在遇到lambda时得到一个新绑定的引用,一切都很好.
但是,在我的GCC 4.8.5(CentOS 7)上,我看到一些行为(在一个更复杂的程序中)表明这是UB,因为f并且引用f.x本身已经死亡.是对的吗?