在c++中创建一个匿名函数执行体采用的是配地的方括号机制[]。
匿名函数的格式如下:
[](参数){函数执行体}
上述匿名函数什么都不捕捉,方括号里面是&、=、=,&foo、bar和this。
&捕捉任何被涉及到的变量。
=通过复制捕捉任何被涉及到的变量。
&,foo除了捕捉涉及到的foo,其他的都通过复制捕捉变量。
bar只捕捉复制的,其他的都不捕捉。
this捕捉本类的
原文:
- [] 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
举一个实例
[=]:
void function(){
int i = 0;
void func = [=]{cout <<i <<endl;};
func();
}
其他的照猫画虎
详情参考:https://en.wikipedia.org/wiki/Anonymous_function#C.2B.2B