I personally feel that C++11 lambda has some conflict with C/C++ function in that, a function local variable's life ends with function, but in FP, lambda is an object thus its variables has life cycle as long as the lambda.
I've got a small test
#include<stdio.h>
int main()
{
auto f=[](int input){
int local=3;
return [=](int x){return input+local+x;};
};
auto f1=f(3);
auto f2=f(4);
printf("%d,%d\n",f1(2),f2(2));
return 0;
}
g++ -std=c++11, it prints "8,9"
It's my expectation for FP, but for C language scope, its behavior should be "undefined", because both "input" and "local" dies after the "f" declaration.
So question:
For both input parameter and internal variable, does lambda object store them somewhere to make sure, they are still available after lambda definition? Or my test is undefined behavior?
Thanks.
Aucun commentaire:
Enregistrer un commentaire