(四)c++11 lambada 与 闭包

lambda

匿名函数

#include <iostream>
#include <stdio.h>
using namespace std;

int main()
{
    // []{}
    auto foo1 = [] {return 1 + 2; };
    cout << foo1() << endl;

    // [](){}
    auto foo2 = [](int x = 1, int y = 2) {return x + y; };
    cout << foo2() << endl;
    
    // [](){}
    auto foo3 = [](int x, int y) {return x + y; };
    cout << foo3(10,2) << endl;
    cout << [](int x, int y) {return x + y; }(10, 30) << endl;

    // []()->{}
    auto foo4 = [](int x = 1, int y = 2)->int {return x + y; };
    cout << foo4() << endl;
    cout << [](int x, int y)->int {return x + y; }(30,11) << endl;
    
    return 0;
}

闭包 mutable

#include <iostream>
#include <stdio.h>
using namespace std;

int main()
{
    int x = 10, y = 20;
    // [] 不截取任何变量,内部也不能改变任何变量
    auto foo = []() mutable {
        // x = 11; 错误
        // y = 22;
        cout << "内部" << endl;
    };
    foo();

    // [a] 值传递,仅能外部截取的变量x操作,只能在内部使用,不能改变外部
    auto foo1 = [x]() mutable {
        x = 11;
        // y = 22; 错误
        cout << "内部" << x << endl;
    };
    foo1();
    cout << "外部" << x << endl;

    // [&a] 引用传递,既可以改变内部也能改变外部值
    auto foo2 = [&x]() mutable {
        x = 11;
        // y = 22;
        cout << "内部" << x << endl;
    };
    foo2();
    cout << "外部" << x << endl;

    // [&]: 截取外部作用域中所有的变量,作为引用传递,内外部都可改变
    auto foo3 = [&]() mutable {
        x = 1;
        y = 2;
        cout << "[&],内部" << x << y<< endl;
    };
    foo3();
    cout << "[&],外部" << x << y << endl;

    // [=]: 外部所有变量,作为值传递,内部可改,外部不可改
    auto foo4 = [=]() mutable {
        x = 33;
        y = 44;
        cout << "[=],内部" << x << y << endl;
    };
    foo4();
    cout << "[=],外部" << x << y << endl;

    // [x, &y] x是值传递,y是引用传递,
    auto foo5 = [x, &y]() mutable {
        x = 99;
        y = 88;
        cout << "[x,&y], 内部" << x << y << endl;
    };
    foo5();
    cout << "[x,&y], 外部" << x << y << endl;

    //[=,&a] 所有都是值传递,仅a是引用传递
    auto foo6 = [=, &x]() mutable {
        x = 121;
        y = 323;
        cout << "[=,&y], 内部" << x << y << endl;
    };
    foo6();
    cout << "[=,&y], 外部" << x << y << endl;
     
    return 0;
}


内部
内部11
外部10
内部11
外部11
[&],内部12
[&],外部12
[=],内部3344
[=],外部12
[x,&y], 内部9988
[x,&y], 外部188
[=,&y], 内部121323
[=,&y], 外部12188

 

posted @ 2020-05-14 19:13  欧阳图图的少年成长记  阅读(148)  评论(0)    收藏  举报