2

Possible Duplicate:
Parentheses at the end of a C++11 lambda expression

#include <iostream>

int main(int argc, char* argv[])
{
    int j;
    [&](){j = 10;}(); // why I need the last rounded parentheses () and what is their purpose ?
    // ...
    return(0);
}

I get almost everything about how the lambda works, my last question is about why i need the last couple of parentheses like reported in the above code.

The blueprint for a lambda is

[](){}

Also, I'm taking an input for my lambda by reference here, I'm directly writing into j with this lambda, but my compiler complains about the fact that this lambda generates an unused value if i don't put the extra () at the end of the lambda.

So, in the end, a lambda is this

[](){}

or this

[](){}()

?

1
  • 1
    Can you explain what exactly are you trying to do with lambda in this context? Commented Oct 28, 2012 at 16:00

3 Answers 3

5

The [](){} defines a temporary lambda functor, the final () invokes its operator() (i.e. the function call operator) => you are defining a (temporary) lambda and calling it on the spot.

You may "see" it better as

([](){})()
 ^^^^^^ ^^ 
   ||    invokes the "function call operator"
 lambda definition
Sign up to request clarification or add additional context in comments.

Comments

4

A lambda function is [](){}. When you add the parenthesis after it, it exectutes the lambda function.

Writing [](){}, you simply declare the function. This gives you the ability to store it with something like auto my_lambda = [](){}, for a later call my_lambda().

2 Comments

as before, stackoverflow.com/questions/13110413/… , i don't really get this behaviour ...
so it's never implicit the fact that that lambda needs to be executed/used.
3

The call operator will immediately-execute the lambda.

int x = [] { return 5; }(); // x == 5

7 Comments

ok, now, why i need to do this ? Lambda functions are not maded to be directly used in the code ? it's not implicit the fact that i want to use lambda where i write them ?
@axis You can store a lambda function and use it whenever you like. You can even pass it to other functions.
@axis: the point of lambdas is exactly to define functors "on the fly".
@axis Lambdas are like functors, but not exactly the same. See this answer -- stackoverflow.com/a/7627218/701092
@axis Yes. As the standard says: "A closure object behaves like a function object." Or technically, "The closure type for a lambda-expression has a public inline function call operator (13.5.4) whose parameters and return type are described by the lambda-expression’s parameter-declaration-clause and trailing-return-type respectively."
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.