/* File: lambda4.cpp An example of a lambda expression capturing a global variable count. This program compiles with GNU g++ with a warning, but not with clang g++ (as of Oct 13, 2021). In GNU g++, calling the returned lambda expression changes the value of the global, even though count is captured by value. */ #include // must #include to use std::function< > // #include using namespace std ; int count=0 ; std::function< int(int) > makeAddXLambda(int x) { return [x,count](int n){ return n+x+(count++) ; } ; } int main () { std::function< int(int) > add3 = makeAddXLambda(3) ; cout << "add3(5) = " << add3(5) << endl ; cout << "count = " << count << endl ; cout << "add3(5) = " << add3(5) << endl ; cout << "count = " << count << endl ; cout << "add3(5) = " << add3(5) << endl ; cout << "count = " << count << endl ; std::function< int(int) > add5 = makeAddXLambda(5) ; cout << "add5(8) = " << add5(8) << endl ; cout << "count = " << count << endl ; cout << "add5(8) = " << add5(8) << endl ; cout << "count = " << count << endl ; cout << "add5(8) = " << add5(8) << endl ; cout << "count = " << count << endl ; }