我試圖通過(可變)lambda中的副本捕獲一個const對象。不過,我的編譯器抱怨說,捕獲的對象是const。在lambda封閉中複製常量對象不可改變
不應該可以將對象作爲非常量來複制嗎?
struct Foo
{
Foo(){}
void Func(){}
};
int main()
{
const Foo foo;
[foo]() mutable { foo.Func(); };
}
使用g ++ 4.7.2編譯:
testcase.cpp: In lambda function:
testcase.cpp:10:29: error: no matching function for call to ‘Foo::Func() const’
testcase.cpp:10:29: note: candidate is:
testcase.cpp:4:7: note: void Foo::Func() <near match>
testcase.cpp:4:7: note: no known conversion for implicit ‘this’ parameter from ‘const Foo*’ to ‘Foo*’
與鐺++ 3.1編譯:
testcase.cpp:10:20: error: member function 'Func' not viable: 'this' argument has type 'const Foo', but function is not marked const
std::async([foo]() mutable { foo.Func(); });
標準文件(或者更確切地說,草案...)定義5.1.2.14 「該類型是相應的被捕獲實體的類型」,所以我想這將包括cv-specifiers。
雖然它並不直觀。
你可以明確地拷貝你的lambda體內部,但我想這不是你想要的。您當然可以將r值參考作爲給定C++ 11的參數。 – CashCow
是什麼問題? – chill
@chill這是一個問題:爲什麼在lambda中複製的foo對象是const? –