I have a basic lambda that looks like this:
auto l = [](){
int i = 0;
cout << i++;
}
Calling this a bunch of times, will keep printing 0. How can I retain i? Can I do this without functors?
Depending on what you want to do with this lambda, you might consider the following alternative:
auto exec = [i = 0]() mutable { cout << ++i << ' '; };
exec(); // 1
exec(); // 2
auto exec2 = exec; // copy state of lambda
exec2(); // 3
exec(); // 3
Using []() { static int i = 0; cout << ++i << ' '; };
instead will result in the sequence 1 2 3 4
being printed.
Live example
Try to think of a lambda as a class with an operator()
. How would you retain state in a class? Have a member. Captures are the equivalent here.
#include <iostream>
auto l = [i=0]()mutable{
std::cout << i++;
};
auto l2=l;
int main(){
l(); // 0
l(); // 1
l(); // 2
l2(); // 0
l2(); // 1
l(); // 3
std::cout << '\n';
}
auto l = [](){
static int i = 0;
// ^^^^^^
cout << i++;
}
should fix your concerns.
In general functions cannot retain inner state without using a local static
variable. There's no difference with using lambdas actually.
If you want to count copies, you can use an ordinary functor class implementation as @Revolver_Ocelot suggested.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With