Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda Expressions

Tags:

c++

c++11

lambda

A point from ISO draft n3290 section 5.1.2 paragraph, point 19:

The closure type associated with a lambda-expression has a deleted (8.4.3) default constructor and a deleted copy assignment operator. It has an implicitly-declared copy constructor (12.8) and may have an implicitly declared move constructor (12.8). [ Note: The copy/move constructor is implicitly defined in the same way as any other implicitly declared copy/move constructor would be implicitly defined. —end note ]

Can any one please ....tell some example for this point to understand?

Is there any chance/way to check the Closure object(type)?

like image 741
user751747 Avatar asked May 31 '11 11:05

user751747


People also ask

Why are they called lambda expressions?

They're being added in as part of Project Lambda. But what is a Lambda expression? The term “Lambda” comes from mathematics, where it's called lambda calculus. In programming, a Lambda expression (or function) is just an anonymous function, i.e., a function with no name.

How is lambda expression represented?

For Lambda expressions, the compiler doesn't translate them into something which is already understood by JVM. Lambda syntax that is written by the developer is desugared into JVM level instructions generated during compilation, which means the actual responsibility of constructing lambda is deferred to runtime.


2 Answers

The closure type associated with a lambda-expression has a deleted (8.4.3) default constructor

int main() {
    auto closure = [](){};
    typedef decltype(closure) ClosureType;

    ClosureType closure2;   // <-- not allowed

    return 0;
}

and a deleted copy assignment operator. It has an implicitly-declared copy constructor (12.8) and may have an implicitly declared move constructor (12.8).

#include <utility>

int main() {
    auto closure = [](){};
    typedef decltype(closure) ClosureType;

    ClosureType closure2 = closure;   // <-- copy constructor
    ClosureType closure3 = std::move(closure);  // <-- move constructor
    closure2 = closure3;              // <-- copy assignment (not allowed)

    return 0;
}
like image 146
kennytm Avatar answered Sep 21 '22 08:09

kennytm


struct LambdaExample{
  // deleted operations = not allowed
  LambdaExample() = delete;
  LambdaExample& operator=(LambdaExample const&) = delete;

  // generated by the compiler:
  LambdaExample(LambdaExample const& other);
  LambdaExample(LambdaExample&& other);

  // anything else a lambda needs
};

For your second question, if you mean that you can look into the implementation, then nope, not possible. It's created on-the-fly by the compiler. If you mean to get the type of the lambda, sure:

auto l = [](){};
typedef decltype(l) closure_type;
like image 42
Xeo Avatar answered Sep 21 '22 08:09

Xeo