Can C 0x Lambda Captures Be Modified without Being Const?
Lambda captures in C 0x typically capture variables by reference, which are inherently constant. However, certain scenarios require the modification of captured variables, raising the question, "Can captured values be made non-const?"
Consider a library functor, foo, with a non-const method, operator(), that needs to be called within a lambda. The code snippet below attempts this but fails to compile:
<code class="c++">struct foo { bool operator () ( const bool & a ) { return a; } }; auto bar = [=] () -> bool { afoo(true); };</code>
The compilation error arises because the lambda's operator() is implicitly marked as const due to the captured values being constant. To resolve this issue, C 0x provides the mutable keyword.
<code class="c++">auto bar = [=] () mutable -> bool { afoo(true); };</code>
By adding mutable, the lambda's operator() is no longer const, allowing the captured variables to be modified within the lambda. This enables the modification of library functors or other non-const captured values as needed within lambdas.
The above is the detailed content of Can C 0x Lambda Captures Be Modified Without Being Const?. For more information, please follow other related articles on the PHP Chinese website!