C++ Mutable Lambdas
In C++, lambda expressions are by default const objects, meaning they cannot modify the variables captured from their enclosing scope. However, there are situations where you may want a lambda expression to modify its captured variables. In such cases, you can use the mutable
keyword to make the lambda expression mutable.
Syntax for Mutable Lambdas:
To create a mutable lambda expression in C++, you need to add the mutable
keyword after the capture list, like this:
[capture_list](parameters) mutable { /* lambda body */ }Scruoe:www.theitroad.com
In this case, the lambda expression can modify the variables that are captured by value.
For example, let's say you have a variable count
that is captured by value in a lambda expression:
int count = 0; auto increment_count = [count]() { count++; };
The lambda expression increment_count
captures count
by value and attempts to modify it. However, since the lambda expression is not mutable, the code will not compile, and you'll get an error.
To make the lambda expression mutable, you can add the mutable
keyword as follows:
int count = 0; auto increment_count = [count]() mutable { count++; };
In this case, the lambda expression can modify the captured variable count
.
Using Mutable Lambdas:
Mutable lambdas are useful when you need to modify the state of an object or variable that is captured by value in a lambda expression. For example, consider the following code:
#include <iostream> #include <vector> int main() { std::vector<int> values{1, 2, 3, 4, 5}; int sum = 0; auto add_to_sum = [sum](int value) mutable { sum += value; }; for (auto value : values) { add_to_sum(value); } std::cout << "Sum of values: " << sum << std::endl; return 0; }
In this code, a lambda expression add_to_sum
is defined that captures sum
by value and adds a given integer value to it. Since the lambda expression is mutable, it can modify the captured variable sum
. The lambda expression is then called in a loop to add all the values in the values
vector to sum
.
The output of this program will be:
Sum of values: 15
As you can see, the lambda expression was able to modify the value of the captured variable sum
, even though it was captured by value and the lambda expression was defined outside of the for
loop.
Overall, mutable lambdas are a powerful feature of C++ that allow you to modify the state of captured variables in lambda expressions. However, you should use mutable lambdas sparingly, as they can make code harder to reason about and can introduce bugs if used incorrectly.