After learning lambda in C++11, I wrote this and got confused by the output.
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;
Output is:
15
5772973
2686617
2686617
What's the reason behind this?
Because undefined behavior.
tmp gets destructed after f1 is assigned, and so tmp_p becomes a dangling pointer. Anything can happen when you dereference it, including sometimes given the right value 15, and sometimes not 5772973.
The same goes for f2, but instead of using a pointer, you use a reference, which references a destructed object, which is also undefined behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With