Tuesday, 25 October 2016

c++ - What does [&] mean before function?




What do the follow row of code mean?



auto allowed = [&](int x, const std::vector&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


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...