Droide Droide - 2 months ago 6
C++ Question

What does [&] mean before function?

What do the follow row of code mean?

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

....

}


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

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

Answer

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
Comments