Brandan Tyler Lasley
Brandan Tyler Lasley

Reputation: 146

Lambda by reference

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;  
};

Upvotes: 3

Views: 99

Answers (2)

Richard Hodges
Richard Hodges

Reputation: 69864

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.

Upvotes: 8

Vlad from Moscow
Vlad from Moscow

Reputation: 310940

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;  
};

Upvotes: 1

Related Questions