| lambda-expressions/more-forms.cc - More forms - mutable and explicit return type. | Lecture 3 - slide 2 : 27 Program 2 |
// Illustration of mutable in context of lambda expressions.
#include <iostream>
#include <string>
int main () {
int p{7};
auto f7 = [p](){++p;}; // COMPILE TIME ERROR: increment of read-only variable p
auto f8 = [p]()mutable{++p;}; // now OK, but strange. Does NOT affect p in main
auto f9 = [&p](){++p;}; // OK: Does affects p in main.
f8(); // A local copy of p is incremented. p in pmain unaffected.
std::cout << "p: " << p << std::endl; // p: 7
f9(); // p in main is incremented, via the reference.
std::cout << "p: " << p << std::endl; // p: 8
}