What is the reason why lambdas have no default constructor? Is there any technical reason behind that, or is it a pure design decision?
Lambda functions may be implemented as closures, but they are not closures themselves. This really depends on the context in which you use your application and the environment. When you are creating a lambda function that uses non-local variables, it must be implemented as a closure.
"A closure is a lambda expression paired with an environment that binds each of its free variables to a value. In Java, lambda expressions will be implemented by means of closures, so the two terms have come to be used interchangeably in the community."
In C++11 and later, a lambda expression—often called a lambda—is a convenient way of defining an anonymous function object (a closure) right at the location where it's invoked or passed as an argument to a function.
The compiler-defined default constructor is required to do certain initialization of class internals.
Lambdas in C++ are a syntactic convenience to allow the programmer to avoid declaring a functor using traditional syntax like
struct my_functor
{
bool operator()(Object &) { /* do something */ return false; }
}
because writing functors using this syntax is considered too long winded for simple functions.
Lambdas offer parameter capture options e.g [=], [&] etc. , to save you declaring variables and initializing them, like you might do in the constructor of a functor object.
So Lambdas don't expose any constructor syntax to you by design.
There is no technical reason a lambda function could not expose a constructor, however if it were to do so it would stop mimicking the design concept it is named for.
With thanks to the commentators under the question.
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