Sto provando a catturare un oggetto const tramite copia in un lambda (mutabile). Il mio compilatore tuttavia lamenta che l'oggetto catturato è const.Oggetto const copiato in chiusura lambda non mutabile
Non dovrebbe essere possibile copiare l'oggetto come non-const?
struct Foo
{
Foo(){}
void Func(){}
};
int main()
{
const Foo foo;
[foo]() mutable { foo.Func(); };
}
compilazione con 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*’
compilazione con clang ++ 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(); });
Il documento standard (o meglio il progetto ...) definisce in 5.1.2.14 che "Il tipo [...] è il tipo dell'entità catturata corrispondente", quindi suppongo che includerebbe gli specificatori cv.
Tuttavia non sembra intuitivo.
Si potrebbe copiare esplicitamente all'interno del proprio corpo lambda ma immagino che non sia quello che stai cercando. Ovviamente potresti prendere come riferimento il valore r come parametro dato che è C++ 11. – CashCow
Qual è la domanda? – chill
@chill Questa è la domanda: perché l'oggetto foo copiato all'interno di lambda è const? –