How / Can C ++ lambdas maintains internal state?

I have a basic lambda that looks like this:

auto l = [](){ int i = 0; cout << i++; } 

Calling this several times will print 0. How can I save i? Can I do this without functors?

+5
source share
4 answers
  auto l = [](){ static int i = 0; // ^^^^^^ cout << i++; } 

should fix your problems.

In common functions, you cannot preserve the internal state without using the local static variable. There is no difference using lambda actually.


If you want to count copies, you can use the usual functor class implementation as @Revolver_Ocelot .

+4
source

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 << ' '; }; []() { static int i = 0; cout << ++i << ' '; }; instead, prints the sequence 1 2 3 4 .

Living example

+12
source

Think of lambda as a class with operator() . How would you save the state in the class? You have a member. Captures here are equivalent.

 #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'; } 
+9
source

If you want i keep its value, you have three options:

  • Declare i as a global variable (Bad).
  • Pass previous i value to function every time (better).
  • Declare i as a static variable (best).

     auto l = []() { static int i = 0; cout << i++ << endl; }; l(); l(); l(); 

    This will give as output:

     0 1 2 
+2
source

All Articles