Possible Duplicate:
What is a lambda expression in C++11?
I found this expression in C++ (one of the most exciting features of C++11):
int i = ([](int j) { return 5 + j; })(6); Why I get the 11? Please explain this expression.
Possible Duplicate:
What is a lambda expression in C++11?
I found this expression in C++ (one of the most exciting features of C++11):
int i = ([](int j) { return 5 + j; })(6); Why I get the 11? Please explain this expression.
[](int j) { return 5 + j; } is a lambda that takes an int as an argument and calls it j. It adds 5 to this argument and returns it. The (6) after the expression invokes the lambda immediately, so you're adding 6 and 5 together.
It's roughly equivalent to this code:
int fn(int j) { return 5 + j; } int i = fn(6); Except, of course, that it does not create a named function. A smart compiler will probably inline the lambda and do constant folding, resulting in a simple reduction to int i = 11;.
[] denote? Whenever I see brackets, I think array.[] contains a list of variables in the outer scope that you want to capture into the inner scope. You can capture things by value or by reference. (When capturing by reference, things are captured using C++ references; the lifetime of function locals is not extended in C++ like it is in C#.) In this particular case, the lambda is not capturing anything from the outer scope.