gpt4 book ai didi

VS2010 中使用 lambda 参数捕获的 C++ 嵌套 lambda 错误?

转载 作者:可可西里 更新时间:2023-11-01 18:26:51 30 4
gpt4 key购买 nike

我正在使用 Visual Studio 2010,它显然在 lambda 上有一些错误行为,并且有这个嵌套的 lambda,其中内部 lambda 返回包装为 std::function 的第二个 lambda(参见 "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]”,断言将按预期通过。这是 VS2010 的错误还是我不了解 lambda 捕获的工作原理?

最佳答案

这不是错误,因为 n 在 lambdas return 语句之后超出范围,因此在您使用它时通过引用捕获无效。

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!

关于VS2010 中使用 lambda 参数捕获的 C++ 嵌套 lambda 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6216232/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com