簡體   English   中英

C++ 嵌套 lambda 在 VS2010 中的錯誤與 lambda 參數捕獲?

[英]C++ nested lambda bug in VS2010 with lambda parameter capture?

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]”,則斷言按預期通過。 這是 VS2010 的錯誤還是我不明白 lambda 捕獲是如何工作的?

這不是一個錯誤,因為在 lambdas return 語句之后n超出了 scope ,因此引用捕獲在您使用它時無效。

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!

這類似於只返回一個簡單引用的情況。 引起你注意的是編譯器沒有發出警告。 所以這不是編譯器中的錯誤,只是缺少警告。

std::function<int()> F(int n)
{
    return [&]{ return n; };  //no warning
}
int& F2(int n)
{
    return n; //warning
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM