Droide Droide - 1 month ago 8
C++ Question

Use parameter lambda function C++

I have this piece of code:

void function1(char c, bool b){

auto get_allowed = [&](int x){
if(b){
.... some code...
}
...some code...
}

get_allowed(0);
...other_code...
}


Can I use b inside the lambda function in this case??

I means, is the same thing to add that parameter into signature of lambda function, something like:

void function1(char c, bool b){

auto get_allowed = [&](int x,bool b){
if(b){
.... some code...
}
...some code...
}

get_allowed(0, false);
...other_code...
}


To clearify, the difference is here:

auto get_allowed = [&](int x){
get_allowed(0);


VS

auto get_allowed = [&](int x,bool b){
get_allowed(0, false);


where b is a parameter of the function function1.

Answer

The [&] capture list makes sure that the variables in the scope surrounding the definition of the lambda can be used by reference in the body of the lambda function.

So yes: in the first snippet, b is usable in the lambda (just don't forget the semi-column to end the function assignment). And you even can change its value (affecting b in get_allowed() would change the value of the parameter b of function1() as it is captured by reference) !

In the second snippet, you pass b as parameter by value. This works differently. There b is the name of a parameter passed by value, and it has nothing to do with the b of the enclosing scope.

Additional remarks

Attention: if your lambda survives the scope that defines it (for example, if you'd return the lambda from function1() or store the value of get_allowed), you could have problems with a capture by reference ; invoking the lambda later in another context could reference variables which no longer exist (dangling reference).

If you prefer a looser coupling, you may consider the [=] capture list instead: it has a similar effect, but the captured variables are passed by value (i.e. no accidental modification nor dangling references). This makes the lambda more independent the context in which it was created.