lambda-expressions/lambda3.cc - A function that returns a function - closure - problems. | Lecture 3 - slide 2 : 27 Program 5 |
// A function that returns the value of a lambda expression - a closure. // Problems! NO compiler warning issued. #include <iostream> #include <string> #include <functional> // std::function std::function<int(int)> f(const int seed0){ int seed{seed0}; // Encapsualted local state return [&seed](int i){ // Returns a closure that captures seed. seed++; return i + seed; }; } int main () { using namespace std; auto g = f(5); // f(5) returns a function that accesses seed. // seed dangles in the closure in g. for(int i = 1; i <= 5; i++) cout << "g(" << i << ") = " << g(i) << endl; // Unpredicatable output }