c++ lambda表达式

在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

作者:first_semon
         
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。如有问题,欢迎交流
原文地址:https://www.cnblogs.com/first-semon/p/5826289.html