l2m2 l2m2 - 3 months ago 9
C++ Question

Confused by lambda output in this case

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?

Answer

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.

Comments