lamda表达式

C++ 11中的Lambda表达式用于定义并创建匿名的函数对象,以简化编程工作。
C++11中,官方似乎一直鼓励大家用lambda表达式,而不是函数对象,lambda表达式更易于使用和理解。
lambda表达式的语法如下:
[capture_block](parameters) exceptions_specification -> return_type {body}
[捕捉快](参数) 异常 -> 返回值类型 {主体}
[] 不捕获任何变量
[=] 拷贝捕获
[&] 引用捕获
[=, &] 拷贝与引用混合
[bar] 指定引用或拷贝
[this] 捕获 this 指针
int i = 1024;
1、创建一个匿名函数并执行
[]{cout << "Hello,Worldn";}();
2、传入参数 auto func = [](int i) { cout << i<<endl;}; func(i);
3、捕获[] [] 不捕获任何变量
4、[=] 拷贝捕获 auto func = [=] { cout << i <<endl;}; // [=] 表明将外部的所有变量拷贝一份到该函数内部 func();
5、[&] 引用捕获 auto fun1 = [&]{cout << &i << endl;};//[&] 表明将外部的所有变量的引用,拷贝一份到该函数内部。 fun1();
6、[=, &] 拷贝与引用混合 auto fun1 = [=, &i]{cout << "i:" << &i << endl;cout << "j:" << &j << endl;}; // 默认拷贝外部所有变量,但引用变量i fun1();
7、[bar] 指定引用或拷贝 auto fun1 = [i]{cout <<i<<&i<<endl;}; auto fun1 = [&i]{cout <<i<<&i<<endl;}; fun1();
8、[this] 捕获 this 指针 auto fun = [this]{this->hello();};// 这里this调用的就是class的对象了 fun();
原文地址:https://www.cnblogs.com/osbreak/p/9212544.html