code explain needed
I couldn't understand that how the value of n remains in this code https://code.sololearn.com/c9PA1zQfGFr0/?ref=app
8/19/2020 2:05:00 PM
ABADA S
8 Answers
New AnswerThis 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 }
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';
I think I understood that but if at every call a new object is created how does n retrieve its value
I hope you noticed there are two n, one in main() and one in the first lambda returned by the function sequence().