patterncppModerate
Using a static variable inside a lambda
Viewed 0 times
usingvariablelambdastaticinside
Problem
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
#include
#include
using namespace std;
int main()
{
vector vec(100);
generate(vec.begin(), vec.end(), [] () { static int i = 0; return i++; });
}Solution
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:
To be functionally equivalent to:
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
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.Code Snippets
auto x = [state1, state2](Param1 param1, Param2 param2){/* Do Stuff */};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);Context
StackExchange Code Review Q#58201, answer score: 16
Revisions (0)
No revisions yet.