1.创建一个匿名函数并执行。Objective-C采用的是上尖号^,而C++ 11采用的是配对的方括号[]。实例如下:
#include <iostream>
[]{ std::cout<< "Hello,Worldn"<<std::endl; }();
结果:Hello,Worldn
我们也可以方便的将这个创建的匿名函数赋值出来调用:
int i = 1024; auto func = [](int i) { // (int i) 是指传入改匿名函数的参数 std::cout<<"i:"<<i<<std::endl; }; func(i);
结果:i:1024
2.捕获选项
[] Capture nothing (or, a scorched earth strategy?)
[&] Capture any referenced variable by reference
[=] Capture any referenced variable by making a copy
[=, &foo] Capture any referenced variable by making a copy, but capture variable foo by reference
[bar] Capture bar by making a copy; don’t copy anything else
[this] Capture the this pointer of the enclosing class
2.1 [] 不捕获任何变量
int i = 1024; auto func = []() { std::cout<<"i:"<<i<<std::endl; }; func();
出错:
vs 报错
error C3493: 无法隐式捕获“i”,因为尚未指定默认捕获模式
error C2064: 项不会计算为接受 0 个参数的函数
g++ 报错:
error: ‘i’ is not captured
要直接沿用外部的变量需要在 [] 中指名捕获。
2.2 [=] 拷贝捕获
int i = 1024; auto func = [=]() { std::cout<<"i:"<<i<<std::endl; }; func();
结果:i:1024
2.3 [&] 引用捕获
int i = 1024; std::cout<<"&i:"<<&i<<std::endl; auto func = [&]() { std::cout<<"&i:"<<&i<<std::endl; }; func();
&i:000000254DCF9A54
&i:000000254DCF9A54
2.4 [=, &] 拷贝与引用混合
int i = 1024; int j = 2048; std::cout<<"&i:"<<&i<<std::endl; std::cout<<"&j:"<<&j<<std::endl; auto func = [=,&i]() {// 默认拷贝外部所有变量,但引用变量i std::cout<<"&i:"<<&i<<std::endl; std::cout<<"&j:"<<&j<<std::endl; }; func();
结果:
&i:000000D4387D97F8
&j:000000D4387D97F4
&i:000000D4387D97F8
&j:000000D4387D9808
2.5 [bar] 指定引用或拷贝