What does [&] mean before function?
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.
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.)
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]
capturevar
by reference[&, var]
specify that the default way of capturing is by reference and we want to capturevar
[=, &var]
capture the variables in scope by value by default, but capturevar
using reference instead