Lambda Capture by Value: Ensuring Non-Const Captured Values in C 0x
When capturing by value in C 0x lambda expressions, the captured values are automatically made constant. This can be an issue if you need to modify the captured values within the lambda.
For example, consider the following lambda that captures a struct foo by value:
<code class="cpp">struct foo { bool operator() (const bool &a) { return a; } }; int main(int argc, char* argv[]) { foo afoo; auto bar = [=] () -> bool { afoo(true); }; return 0; }</code>
This code will not compile because the operator() method of foo is declared as const. To fix the issue, you can make the operator() method non-const:
<code class="cpp">struct foo { bool operator() (bool &a) { return a; } };</code>
However, this is not always a desirable solution. In some cases, you may want to capture a value by value but still ensure that it is not modified within the lambda.
To achieve this, you can use the mutable keyword. By declaring the lambda as [=] () mutable -> bool, you allow the lambda to modify the captured values.
Example:
<code class="cpp">auto bar = [=] () mutable -> bool { afoo(true); };</code>
In this example, the lambda can now modify the captured afoo object, even though it is captured by value.
The above is the detailed content of How Can I Modify Captured Values in C 0x Lambdas When Capturing by Value?. For more information, please follow other related articles on the PHP Chinese website!