What does [&] mean before function?

C++

C++ Problem Overview


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);

C++ Solutions


Solution 1 - C++

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

Solution 2 - C++

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.

Solution 3 - C++

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDroideView Question on Stackoverflow
Solution 1 - C++nishantsinghView Answer on Stackoverflow
Solution 2 - C++BathshebaView Answer on Stackoverflow
Solution 3 - C++KristófView Answer on Stackoverflow