samedi 26 août 2017

Passing references and pointers to lamdas

I am writing code that passes references to lamda 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?

Aucun commentaire:

Enregistrer un commentaire