Search code examples
c++recursiongeneric-lambda

Inner working of lambda functions when wrapper function is called recursively


Consider the following code:

int foo() {
    int lf = [/*captures*/]() {/*body*/};
    if(/*some condition*/) { return /*value*/; }
    foo();    //recursive call
}

Now, in this code, whenever the function foo is called recursively, an activation record of foo will be pushed on to the stack. What I was wondering about is that, is the lambda function included in the record with its definition? Umm..this ain't helping


Solution

  • Firstly:

    int lf = [/*captures*/]() {/*body*/};
    

    is incorrect code, it should be

    // case 1. lambda is automatic
    auto lf = [/*captures*/]() {/*body*/}; // closure object
    

    or (provided that lambda returns something compatible to int)

    // case 2. lambda is temporary
    int lf = [/*captures*/]() {/*body*/} (); /* calling object created */
    

    lambda expression is a shorthand notation for creation of object with a unique class (very simplified, you have to look in standard or in language reference for full description):

    class Closure {
        /* members storing captured values or references */ 
    public:
        return-type  operator( /* argument list*/ ) { /*body*/ };
    }
    

    In first case lambda would be stored in stack, in second case it is a temporary object.

    So lambda with a capture list would store such object, i.e. all captured values exactly where you instructed it to store lambda object, in your case it's automatic storage (so called, "stack"). Using a capture-less lambda is no different from declaring a function and using a pointer to it, there is no storage associated with it and it can be casted to a function pointer.