问题描述
我使用Visual Studio 2010,它显然在lambdas有一些错误的行为,并有这个嵌套的lambda,其中内部lambda返回第二个lambda包装为std ::函数(cf. ):
I'm using Visual Studio 2010, which apparently has some buggy behavior on lambdas, and have this nested lambda, where the inner lambda returns a second lambda wrapped as a std::function (cf. "Higher-order Lambda Functions" on MSDN):
int x = 0;
auto lambda = [&]( int n )
{
return std::function<void()>(
[&] // Note capture
{
x = n;
}
);
};
lambda( -10 )(); // Call outer and inner lambdas
assert( -10 == x ); // Fails!
这会进行编译,但在断言时失败。具体来说,内部lambda中的n未初始化(0xCCCCCCCC),但x已成功修改为其值。如果我将内部lambda的捕获子句改为[&,n],则assert如预期那样传递。这是VS2010的一个错误还是我不明白lambda捕获如何工作?
This compiles but fails at the assert. Specifically, n in the inner lambda is uninitialized (0xCCCCCCCC), but x is successfully modified to its value. If I change the inner lambda's capture clause to "[&,n]", the assert passes as expected. Is this a bug with VS2010 or have I not understood how lambda capture works?
推荐答案
这不是一个错误,因为 n
在lambdas return语句之后超出作用域,因此通过引用获取的捕获将在您使用它时失效。
It is not a bug, since n
goes out of scope after lambdas return statement, thus the capture by reference is invalidated by the time you use it.
int x = 0;
auto lambda = [&]( int n )
{
return std::function<void()>( // n is local to "lambda" and is destroyed after return statement, thus when you call the std::function, the reference capture of n is invalid.
[&]
{
x = n; // Undefined behaviour
}
);
};
auto tmp = lambda(-10);
// n is no longer valid
tmp(); // calling tmp which uses reference of n which is alrdy destroyed.
assert( -10 == x ); // Fails!
这篇关于C ++嵌套lambda bug在VS2010与lambda参数捕获?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!