jeudi 1 septembre 2016

confused by lambda in c++11

After learning lambda in c++11, i write code as below. i get confused by the output. Anyone could tell me the reason ?

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(mingw5.3 debug):

15

5772973

2686617

2686617

Aucun commentaire:

Enregistrer un commentaire