The C++ mutable lambda expressions as stateful function objects

Question | Jul 13, 2016 | nextptr 

The variables captured by value (or copy) cannot be modified in a lambda expression by default. However, this default behavior can be overridden by the mutable qualifier. A mutable lambda expression is allowed to change the variables that are captured by value. As an example, foo is a mutable lambda expression below that can modify the value-captured variable x:

int x = 0;
auto foo = [x] () mutable { 
    /* "x" cannot be modified without 
         keyword mutable. */
     return x;

A lambda expression is essentially a function object with an overloaded function-call operator (operator ()). That overloaded function-call operator is const unless the lambda expression is declared mutable.

It 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:

 // call foo
std::cout << foo() << " ";

// assign foo to bar
auto bar = foo;

// call foo again
std::cout << foo() << " ";

// call bar
std::cout << bar() << " ";

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 Explanations for details):

2015 nextptr