Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How/Can C++ lambdas retain inner state?

Tags:

c++

lambda

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?

like image 658
val Avatar asked Jun 26 '16 10:06

val


3 Answers

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

like image 88
Hiura Avatar answered Oct 13 '22 04:10

Hiura


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';
}
like image 30
Marc Glisse Avatar answered Oct 13 '22 04:10

Marc Glisse


 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.

like image 35
πάντα ῥεῖ Avatar answered Oct 13 '22 04:10

πάντα ῥεῖ