code explain needed | Sololearn: Learn to code for FREE!


code explain needed

I couldn't understand that how the value of n remains in this code

8/19/2020 2:05:00 PM


8 Answers

New Answer


This is an overview, actual implementation will be different. n value is accessed in inner most lambda's function call operator int main() { auto f = function(start, end).operator()(increment); function returns outer object. call operator()(increment) on that, which return object of inner f has object of inner call f() on that object } auto function() { class outer { outer operator()(increment) { class inner { inner operator()(){ actual works n += increment return temp } } inner (n, other parameter b// object of inner not shown) return inner; } } outer (variables not shown); //object of outer return outer object }


~ swim ~ hello master😊


C++ expands/converts a lambda function to a functor behind the scene. A functor is a class\struct that overloads function call "()" operator. The innermost lambda is referring/accessing/modifying the variables from the outer scope by value. The compiler when expanding the lambda will create a member variable that will store the value of 'n'. In the subsequent method calls that variable will be accessed/modified and returned. At every call a new object is created with updated value of 'n';


thank you master ~ swim ~ I got it


lion ofcourse I did , I think these are two variables not one aren't?


I think I understood that but if at every call a new object is created how does n retrieve its value


ABADA S Glad to hear it πŸ™‚πŸ™πŸ‘


I hope you noticed there are two n, one in main() and one in the first lambda returned by the function sequence().