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 main
was 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
.
source
share