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
哪個編譯器是正確的嗎?
[This](http://stackoverflow.com/questions/3772867/lambda-capture-as-const-reference)可能是你的興趣。爲了筆直,我不認爲你的問題是重複的:) –
值得注意的是,在啓用優化的情況下,VC也應用RVO,導致只有一次調用'X(X const&)'。 – Oktalist
@skypjack:你確定lambdas構造一個const成員嗎? http://ideone.com/RQ7OjC我認爲數據成員不一定是const,只有'operator()'是。 – JohnB