小编l2m*_*2m2的帖子

在这种情况下被lambda输出混淆

在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)

这背后的原因是什么?

c++ lambda c++11

3
推荐指数
2
解决办法
71
查看次数

标签 统计

c++ ×1

c++11 ×1

lambda ×1