is it safe to modify variables in the via closure from the inner frame of a lambda that was create from a function that no longer function exists
c++, c++11
Solution
Yes it is.
By specifying `[=]` you made a copy of the local variable, and that copy is stashed, somewhere, in the lambda. The expression `c++` uses that local copy, which will live as long as the lambda does.
Note that the `mutable` would not have been necessary had `c` being referencing an external variable; its presence is made necessary by the fact that `c` is captured by copy and thus lives within the lambda "body".
Problem
This works on g++ 4.7 ``` #include <iostream> #include <functional> std::function<int()> make_counter() { return []()->std::function<int()> { int c=0; return [=]() mutable ->int { return c++ ; }; }(); } int main(int argc, char * argv[]) { auto count1= make_counter(); auto count2= make_counter(); std::cout << "count1=" << count1() << std::endl; std::cout << "count1=" << count1() << std::endl; std::cout << "count2=" << count2() << std::endl; std::cout << "count1=" << count1() << std::endl; std::cout << "count2=" << count2() << std::endl; return 0; } ``` It seems like I should be able to do this because c no longer exists after make_function returns, but it is does ``` count1=0 count1=1 count1=2 count2=0 count1=3 count2=1 ``` I'm guessing that the [=] makes it so the value of c stored and mutable is allows for the stored value to modified though I just want to make sure. Valgrind doesn't complain about this at all. Every time I call make_counter, valgrind reports an additional allocation and free, so I assume the lambda meta programming code is inserting the allocation code for the memory for variable . I'm wonder if this is Cxx11 compliant or if it's just g++ specific. assuming the answer is correct, I could simplify make_counter to ``` std::function<int()> make_counter() { int c=0 ; return [=]() mutable ->int { return c++ ; }; } ```