Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused by lambda output in this case

Tags:

c++

c++11

lambda

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?

like image 944
l2m2 Avatar asked Dec 21 '25 01:12

l2m2


1 Answers

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.

like image 84
Rakete1111 Avatar answered Dec 23 '25 13:12

Rakete1111