doron
doron

Reputation: 28872

Passing references and pointers to lambdas

I am writing code that passes references to lambda expressions so I decided to check out a few simple examples using g++-7

The code:

int i = 2;
auto f = [i]() {
    printf("i = %d\n", i);
};
printf("incrementing i to  %d\n", ++i);
f();

Prints

incrementing i to  3
i = 2

as expected because the lamda make a copy of i for later and:

int i = 3;
int& j = i;
auto g = [j]() {
    printf("j = %d\n", j);
};
printf("incrementing i to  %d\n", ++i);
g();

prints

incrementing i to  4
j = 3

yet:

i = 4;
int* k = &i;
auto h = [k]() {
    printf("*k = %d\n", *k);
};
printf("incrementing i to  %d\n", ++i);
h();

prints

incrementing i to  5
*k = 5

Now normally references behave like pointers that do not need to be dereferenced (and cannot be changed) but with lamda capture this is not the case. Is this standard expected behaviour and if so why does this differ from normal reference behaviour?

Upvotes: 2

Views: 273

Answers (2)

jederik
jederik

Reputation: 372

To pass i as a reference use

auto f = [&i]() {
  printf("i = %d\n", i);
};

(Note the & prefix in the capture)

It doesn't matter wether i was originally declared as a reference or not.

Upvotes: 0

R Sahu
R Sahu

Reputation: 206577

Unless you use & in the capture, a lambda expression captures by value. Regardless of whether you capture i or j, unless you use &i or &j, the variable is captured by value.

That is no different than a regular function.

void foo(int i) {}
void bar(int& i) {}

int i;
int& j = i;

foo(i); // Passed by value
foo(j); // Passed by value also.

bar(i); // Passed by reference
bar(j); // Passed by reference also.

Upvotes: 3

Related Questions