This answer is late to the party, but I thought this needed to be said:
In most cases when you think static is a good idea for shared state, you should at least consider dependency injection instead.
In other words:
Is using a static variable in a lambda function ok, or considered a bad practice?
It is perfectly valid C++, but consider using an injected seed instead:
int main()
{
vector<int> vec(100);
int count = 0;
// look ma', no static!
generate(vec.begin(), vec.end(), [&count] () { return count++; });
}
In this (simplistic) example, the two are functionally equivalent. In practice though, static
shares state between calls, even when you don't want it to (e.g. you may want to call this from multiple threads in the future, each with it's own count
).
Both are acceptable and correct C++ (YMMV), but the [&count]
alternative leads to less (hidden) side effects, more testable code, more re-usable code and a better habbit to cultivate in written code.
std::iota
. – chris Jul 27 '14 at 16:24