dimanche 4 janvier 2015

Lambdas and capture by reference local variables : Accessing after the scope

I am passing my local-variables by reference to two lambda. I call these lambdas outside of the function scope. Is this undefined ?



std::pair<std::function<int()>, std::function<int()>> addSome() {
int a = 0, b = 0;
return std::make_pair([&a,&b] {
++a; ++b;
return a+b;
}, [&a, &b] {
return a;
});
}

int main() {
auto f = addSome();
std::cout << f.first() << " " << f.second();
return 0;
}


If it is not, however, changes in one lambda are not reflected in other lambda.


Am i misunderstanding pass-by-reference in context of lambdas ?


I am writing to the variables and it seems to be working fine with no runtime-errors with output


2 0. If it works then i would expect output 2 1.


Aucun commentaire:

Enregistrer un commentaire