Should all lambda declarations be persistent?

Lambda object declarations ( std::function<>() / auto lambda = []()... ) are always literals, right? So this means that for clarity, etiquette coding, and even performance, we must declare them const static in the same way as any other limited literal constant?

+7
c ++
source share
1 answer

Lambda object declarations (std :: function <> () / auto lambda = ...) are always literals, right?

No, lambdas are not literals. They can capture state from the covering area and can be non-constant. Consider:

 int f(int a, int b) { auto lambda = [=](int x) { return a*x; }; return lambda(b); } 

If you add static , the lambda variable will be shared by all code using f , and it will only be initialized on the first call, capturing the value of a from the first call to f . Without its static , each call to f will use its own first argument.

While the example is very artificial, I hope this helps clear the point.

+5
source share

All Articles