Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda by reference

Tags:

c++

lambda

c++14

I was wondering if the standard allows you to pass all members by reference using the =. So for instance, this works

int i = 0;
auto f = [&i]() {
    i = 1;  
};

However, this does not and neither does putting an & in behind of the =.

int i = 0;
auto f = [=]() {
    i = 1;  
};
like image 894
Brandan Tyler Lasley Avatar asked Nov 18 '25 11:11

Brandan Tyler Lasley


2 Answers

what you mean is:

int i = 0;
auto f = [&]() {
    i = 1;  
};

[=] captures everything mentioned in the lambda's body by value.

[&] captures everything mentioned in the lambda's body by reference.

like image 109
Richard Hodges Avatar answered Nov 20 '25 04:11

Richard Hodges


In this lambda expression

int i = 0;
auto f = [=]() {
    i = 1;  
};

captured variable i that is a data member of the lambda is changed within lambda. So you have to write

int i = 0;
auto f = [=]() mutable {
    i = 1;  
};

If you want that the i would be captured by reference you should write

int i = 0;
auto f = [=,&i]() {
    i = 1;  
};
like image 20
Vlad from Moscow Avatar answered Nov 20 '25 03:11

Vlad from Moscow