格式: [...](...) 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;