c++lambda

How/Can C++ lambdas retain inner state?


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?


Solution

  •  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.