Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why closure types / lambdas have no default constructor in C++

What is the reason why lambdas have no default constructor? Is there any technical reason behind that, or is it a pure design decision?

like image 511
Vincent Avatar asked Dec 16 '16 22:12

Vincent


People also ask

Are closures and lambdas the same?

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.

Is a closure a lambda?

"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."

What is the lambda keyword used for what is a closure?

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.

Are default constructors necessary?

The compiler-defined default constructor is required to do certain initialization of class internals.


1 Answers

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.

like image 104
JimmyNJ Avatar answered Oct 28 '22 19:10

JimmyNJ