为什么lambda函数通过const捕获值

时间:2016-11-09 11:29:51

标签: c++ lambda

    #include <iostream>

using namespace std;
int main ()
{
  int x=0;
//     auto lambda=[x](){
//       x++;//we cannot increment x as it is const
//       cout<<x<<endl;
//   };
  auto lambda=[x]() mutable{
      x++;
      cout<<x<<endl;
  };

  lambda();

  return 0;
}

这里通过使const按值捕获来获得好处。通过引用捕获是有意义的,因为调用者可以确定传递的参数不会改变。

0 个答案:

没有答案