Different definitions of the same lambda

I recently opened this discussion, from which the following problem arises. This question is a continuation of this discussion. Here is the code:

#include <iostream>
#include <functional>

using namespace std;

std::function<int(void)> mylambda(int starter){
    return [starter]() mutable {
        return ++starter;
    };
}

void tester_wrapper(const std::function<int(void)>& cb, int counter){
    if (counter == 10)
        return;
    else{
        cout << cb() << endl;
        tester_wrapper(cb, counter + 1);
    }
}

void tester(const std::function<int(void)>& cb){
    tester_wrapper(cb, 0);
}

int main()
{
    auto getNum = mylambda(1);

    tester(getNum);
    tester(getNum);
}

In this case, the code does what I expected, more specifically it prints all numbers from 2 to 21. However, if my function mainwas like this:

int main()
{
    auto getNum = ([](int starter) {
        return [starter]() mutable {
            return ++starter;
        };
    })(1);

    tester(getNum);
    tester(getNum);
}

Then the output will be a number from 2 to 11 repeated twice. I cannot explain why it produces this conclusion, even if the difference between the two parts of the code is where and how the function is defined mylambda.

+4
source share
1 answer

std::function . . std::function -.

std::function. , , std::function, const. . tester . Temporaries , spring .

std::function . , tester .

+8

Source: https://habr.com/ru/post/1692159/


All Articles