C++11 Lambda表达式

格式:   [...](...) mutable throwSpec ->retType {....}

1. [...] 表示引入的外部变量 

比如:

int a{0};
int b{1};
auto temp = [a,&b](){std::cout<<a<<std::endl;
std::cout<<++b<<std::endl;};
temp();
std::cout<<b<<endl;

如果直接使用[=] 表示引入所有的外部自动变量,以传值方式。 ([&] 以引用方式)
注意:以传值方式传递时,默认情况下在表达式内不能修改变量值。使用mutable关键字后可以

2.(...)表示传递的参数

int a{0};
int b{1};
auto temp = [a,&b](const std::string p_strTemp){std::cout<<a<<std::endl;
std::cout<<++b<<std::endl;
std::cout<<p_strTemp<<std::endl;
};
temp("test");
std::cout<<b<<endl;

3.mutable 关键字

平时用于强制更改为可用的,比如声明一个变量为mutable,在const函数中,也可以修改该变量。

这里作用为:传值引入的变量,可以被修改

int a{ 0 };
int b{ 1 };
auto l_temp =[a, &b] ()mutable {std::cout << ++a << " " << ++b << std::endl; };
l_temp();

4.throwSpec 异常描述

和平时写法一样 ,

[a, &b] ()mutable throw(int,std::exception){....}

5.->retType 返回值

也可以不指定

int a{0};
int b{1};
auto temp = [=]->int{return a+b;};
std::cout<<temp()<<endl;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值