lambda表达式详解


表达式定义:

[ capture-list ] ( params ) mutable(optional) exception attribute -> ret { body }    (1)    
[ capture-list ] ( params ) -> ret { body }  (2)    
[ capture-list ] ( params ) { body }     (3)    
[ capture-list ] { body }    (4)

上述四种表达式的定义,第一种是Full declaration;第二种是常用模式;第三种是忽略返回值的形式(函数体只是一个return语句,则可以自推断返回类型,否则是void);第四种是忽略返回值和参数列表的形式。

简单示例:

下面就是忽略返回值和函数列表的形式(4):

auto f = []{return 42; };
cout << f() << endl;

带有参数列表的形式(3):

auto f = [](const string &a, const string &b){return a.size() < b.size(); };
cout << f("whoareyou", "whereareyou") << endl;

使用捕获列表(只是值捕获,更复杂的形式在后面介绍):

    int size = 4;
    auto f = [size](const string &str){return str.size() > size; };
    cout << f("who") << endl; // false

如果是引用捕获:

    int size = 4;
    auto f = [&size](const string &str){return str.size() > size; };
    cout << f("who") << endl;
    size = 2;
    cout << f("who") << endl;

当使用引用方式捕获一个变量时,必须保证在lambda表达式执行时变量是存在的。

捕获列表可以是如下形式:

[a,&b]  where a is captured by value and b is captured by reference.
[this]  captures the this pointer by value
[&]  captures all automatic variables odr-used in the body of the lambda by reference
[=]  captures all automatic variables odr-used in the body of the lambda by value
[] captures nothing

默认情况下,对于一个值被拷贝的变量,表达式不会改变其值。如果希望改变其值,必须在参数列表首加上关键字mutable

    int size = 4;
    auto f = [size](const string &str) mutable 
        { 
            size--; 
            cout << size << endl;      
            return str.size() > size; 
        };
    cout << f("wsho") << endl; // 先输出 3, 然后是 true
    cout << f("o") << endl;  // 先输出2, 然后是 false

下面解释上述输出的原因:

上述lambda表达式,编译器将其翻译成一个未命名类的未名名对象。

对上述表达式,将产生类似于下面的类:

class comp
{
    comp(int sz):size(sz){}
    bool operator()(const string &s) const
    {
        size--;
        cout << size << endl;
        return str.size() > size;
    }
    private:
        int size;
}

这也解释了上述由3变为2的过程。

指定返回类型

严格来说上述表达式的函数体中包含多行除return以外的语句,返回类型是void的。但是却仍然正确,只能说是不符合标准但却被编译器(MSVCGCC)接受的行为。

    int size = 4;
    auto f = [size](const string &str) mutable ->bool 
    { 
        size--; 
        cout << size << endl;     
        return str.size() > size; 
    };
    cout << f("wsho") << endl;
    cout << f("o") << endl;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值