在C++ 11中学习lambda之后,我写了这个并且对输出感到困惑.
auto f1 = [] () {
int tmp = 10;
int *tmp_p = &tmp;
return [tmp_p] (int x) {
return *tmp_p + x;
};
}();
auto f2 = []() {
int tmp = 10;
return [&tmp] (int x) {
return tmp + x;
};
}();
cout << f1(5) << endl;
cout << f1(5) << endl;
cout << f2(5) << endl;
cout << f2(5) << endl;
Run Code Online (Sandbox Code Playgroud)
输出是:
15
5772973
2686617
2686617
Run Code Online (Sandbox Code Playgroud)
这背后的原因是什么?