ExampleBy default, the implicit Previous Next IntroThe variables captured by value (or copy) cannot be modified in a lambda expression by default. Let's take an example of a lambda that captures two variables, one by value and the other by reference from its outer scope:
As shown above, it is an error to modify a variable that is captured by value, but a variable captured by reference can be modified in the lambda. A lambda expression is essentially a function object with an overloaded
function-call operator (operator ()). That overloaded function-call operator is
However, this default behavior can be overridden by the
Mutable Lambda as Stateful Function ObjectIt might not be obvious that mutable lambda expressions are like stateful function objects. The captured variable x is the state of foo, which is changed every time foo is called. Consider the following code to see what is so interesting about it:
In brief, we
call foo and then assign it to another variable bar, and then we call foo (again) followed by a call to bar. What would be the output of the above? Select the correct answer below (check the 06 Aug 2017 This post is in continuation to Lambdas in C++. Till now we covered basics of functors and lambdas in C++. We will cover Mutable lambdas in this post. Mutable LambdasObject captured in lambda are immutable by default. This is because
Assembly code for lambda
As you can see that
Using
If we see the assembly code for same code the generated functor after adding mutable keyword looks like:
We can clearly see that In general lambda declaration
That’s it for mutable lambdas. I think we covered basics of lambdas. We will start with R-value reference from next blog post. Till then Sayonara. |