Lambda Capture and Constness in C 0x
A common question arises when working with lambda expressions in C 0x: is there a way to capture by value and at the same time prevent the captured value from being made const?
The C language standard specifies that lambda expressions that capture variables by value do so in a const manner. This means that the captured value cannot be modified inside the lambda. However, in certain scenarios, it may be necessary to capture a variable by value but still modify its value.
For example, consider a library functor with a non-const operator() method that we want to capture and call in a lambda. The following code will not compile:
<code class="cpp">struct foo { bool operator () ( const bool & a ) { return a; } }; int main() { foo afoo; auto bar = [=] () -> bool { afoo(true); }; return 0; }</code>
The error here is that the lambda expression's operator() is declared as const due to the surrounding [=] capture list. To fix this, we can use the mutable keyword. By adding mutable to the lambda capture list, we allow the lambda to modify captured variables, even those captured by value:
<code class="cpp">auto bar = [=] () mutable -> bool { afoo(true); };</code>
This modification makes the lambda's operator() not const, allowing us to call the non-const operator() of the afoo object.
Therefore, to capture by value in a lambda expression and prevent the captured value from being const, use the mutable keyword in the capture list. This allows the lambda to modify the captured variable without causing compilation errors.
The above is the detailed content of How to Capture by Value and Modify Captured Variables in C Lambda Expressions?. For more information, please follow other related articles on the PHP Chinese website!