Is using a static variable in a lambda function ok, or considered a bad practice? The code below works as intended (fills a vector with consecutive numbers).#include <iostream>#include <vector>#include <algorithm>using namespace std;int main(){    vector<int> vec(100);    generate(vec.begin(), vec.end(), [] () { static int i = 0; return i++; });}
Using a static variable inside a lambda
c++;c++11
Yes it is perfectly valid.lambdas in C++ were designed to be functionally equivalent to functors that were used a lot in C++03.So you can consider:auto x = [state1, state2](Param1 param1, Param2 param2){/* Do Stuff */};To be functionally equivalent to:   struct AnonClassX{    State1  state1;    State2  state2;    AnonClassX(State1 state1, State2 state2)       : state1(state1)       , state2(state2)    {}    returnValue operator()(Param1 param1, Param2 param2) const    {         /* Do Stuff */    }};AnonClassX   x(state1,state2);It is quite normal to use static variables in functions and methods. Lambda is just a shorthand for creating an anonymous class with state and an operator()() to make it act like a function. So it should be very normal to put static members inside it.