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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With