2016-12-03 75 views
13

考慮下面的程序:VC++ 15調用lambda捕獲的錯誤拷貝構造函數?

#include <iostream> 
struct X { 
    X() = default; 
    X (X &) { std::cout << "non-const called" << std::endl; } 
    X (X const &) { std::cout << "const called" << std::endl; } 
    int i() const { return 7; } 
}; 

auto f() { 
    X x; 
    auto lambda = [=]() { return x.i(); }; 
    return lambda; 
} 

int main() 
{ 
    auto lambda = f(); 
    std::cout << lambda() << std::endl; 
    return 0; 
} 

用VC++ 15,我得到的輸出

const called 
const called 
7 

鏗鏘3.9,我得到

non-const called 
7 

哪個編譯器是正確的嗎?

+1

[This](http://stackoverflow.com/questions/3772867/lambda-capture-as-const-reference)可能是你的興趣。爲了筆直,我不認爲你的問題是重複的:) –

+0

值得注意的是,在啓用優化的情況下,VC也應用RVO,導致只有一次調用'X(X const&)'。 – Oktalist

+0

@skypjack:你確定lambdas構造一個const成員嗎? http://ideone.com/RQ7OjC我認爲數據成員不一定是const,只有'operator()'是。 – JohnB

回答

2

我會說鏗鏘是對的。
當lambda捕獲x並且返回值的構造函數被優化時,最適合的構造函數僅被調用一次。
這就是爲什麼您只能獲得一個名爲的非常量


關於複製,省音和RVO進一步詳情,請參閱herehere