73

What does the following code mean?

auto allowed = [&](int x, const std::vector<int>&vect){

....

}

I mean, what does [&] do? Is it a function with the same name of the variable?

Because it is used in this way: unsigned short ok = get_allowed(0, vect);

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Droide
  • 1,807
  • 2
  • 17
  • 30
  • 1
    It's a capture list for a lambda (c.f http://en.cppreference.com/w/cpp/language/lambda ) – king_nak Sep 30 '16 at 10:16
  • It is not a function but a lambda. You should read up on those – Hayt Sep 30 '16 at 10:16
  • Just a heads up, I closed [this](http://stackoverflow.com/questions/12262019/c-operator) as a dupe of this question. IMHO the answers here are more detailed. – NathanOliver Sep 30 '16 at 11:55

3 Answers3

132

It means that the lambda function will capture all variables in the scope by reference.

To use other variables other than what was passed to lambda within it, we can use capture-clause []. You can capture by both reference and value, which you can specify using & and = respectively:

  • [=] capture all variables within scope by value
  • [&] capture all variables within scope by reference
  • [&var] capture var by reference
  • [&, var] specify that the default way of capturing is by reference and we want to capture var
  • [=, &var] capture the variables in scope by value by default, but capture var using reference instead
nishantsingh
  • 4,537
  • 5
  • 25
  • 51
18

It's a lambda capture list and has been defined in C++ from the C++11 standard.

[&] It means that you're wanting to access every variable by reference currently in scope within the lambda function.

It's your job to ensure that the referred objects are still in scope at the point the closure is invoked, else the program behavior is undefined.

AAEM
  • 1,837
  • 2
  • 18
  • 26
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
11

It defines a Lambda expression, which is basically a function without a name. It has parameter list (int x, const std::vector<int>&vect) and a function body { ... }. But it also has a capture list in the beginning [&]. If you want to access a variable (which is not a parameter) from the body of the lambda expression, you have to make the expression "take the variable with itself", so that the variable can be used later when the lambda expression will be executed.

You can either provide a list of variables, or use "all" to capture all of them. [&] means capturing all of them by reference, and [=] would mean to capture all of them by value.

(If you use [&], note that the lambda body will use the value of the variable at the time the lambda is executed, and not the value which was valid when you created the lambda! This is because you do not have a copy of the value, only a reference to it.)

Kristóf
  • 141
  • 6