I am trying to use lambda
inside a project, but I think that I have something missing in the closing area. I tested this piece of code that somehow simplifies my problem.
#include <iostream>
#include <functional>
using namespace std;
void tester_wrapper(std::function<int(void)> cb, int counter){
if (counter == 10)
return;
else{
cout << cb() << endl;
tester_wrapper(cb, counter + 1);
}
}
void tester(std::function<int(void)> cb){
tester_wrapper(cb, 0);
}
int main()
{
auto getNum = ([](int starter) {
return [starter]() mutable {
return ++starter;
};
})(1);
tester(getNum);
tester(getNum);
}
After the first call, the tester
captured variable starter
is reset, so the same output is printed twice.
What should I do to avoid this internal counter ( starter
) lambda behavior ? In fact, the second call tester
should print 10 numbers, starting with 12 instead of 2.
EDIT
Thanks for answers. I did not think I was passing a copy tester_wrapper
, so I found this solution:
#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);
}
, getNum
, "" , mylambda
.
( ?)