Junior — Middle
How is mutability used when working with lambda expressions in programming?
sobes.tech AI
Answer from AI
In C++, lambda expressions can capture variables from the surrounding context. Mutability here refers to whether you can modify the captured variables inside the lambda.
By default, lambdas are const, meaning you cannot modify captured variables unless you specify mutable.
Example:
int x = 10;
auto lambda = [x]() mutable {
x += 5; // can modify local copy of x
std::cout << x << std::endl;
};
lambda(); // prints 15
std::cout << x << std::endl; // x outside remains 10
Using mutable allows changing the captured variables inside the lambda, but does not affect the original variables outside.