Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should all lambda declarations be const static?

Tags:

c++

Lambda object declarations (std::function<>() / auto lambda = []()...) are always literals, right? So does that mean we should, for clarity, coding etiquette and even performance, always declare them const static just like any other scoped literal constant?

like image 907
quant Avatar asked Jul 05 '13 13:07

quant


1 Answers

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

No, lambdas are not literals. They can capture state from the enclosing scope and that can be non-const. Consider:

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

If you add static there, the variable lambda will be shared by all the code that uses f, and it will only be initialized on the first call capturing the value of a from the first call to f. By not having it static each call to f will use it's own first argument.

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

like image 187
David Rodríguez - dribeas Avatar answered Sep 17 '22 12:09

David Rodríguez - dribeas