C++11 C++;11-lambda函数在捕获中传递向量并对其进行修改

C++11 C++;11-lambda函数在捕获中传递向量并对其进行修改,c++11,lambda,C++11,Lambda,我有以下代码: #include <iostream> #include <functional> #include <vector> int main () { std::vector<int> kk; kk.push_back(2); std::function<int(int)> foo = std::function<int(int)>([kk](int x) { kk.push_ba

我有以下代码:

#include <iostream> 
#include <functional>
#include <vector>

int main () {
  std::vector<int> kk;
  kk.push_back(2);
  std::function<int(int)> foo = std::function<int(int)>([kk](int x)
  {
      kk.push_back(1);
      return kk[0]+1;
  });

  std::cout << "foo: " << foo(100) << '\n';

  return 0;
}
#包括
#包括
#包括
int main(){
std::矢量kk;
kk.推回(2);
std::function foo=std::function([kk](intx)
{
kk.推回(1);
返回kk[0]+1;
});

std::cout默认情况下,闭包类型将其
运算符()
声明为
const
限定的成员函数。这意味着不能在lambda内部修改复制捕获的对象。要使
运算符()
成为非
const
成员函数,必须将lambda
标记为可变的

std::function<int(int)> foo{[kk](int x) mutable
{
    kk.push_back(1);
    return kk[0]+1;
}};
std::函数foo{[kk](intx)可变
{
kk.推回(1);
返回kk[0]+1;
}};

(我还冒昧地删除了声明中的双类型规范)

当然,请记住,捕获中生成的
kk
副本是lambda对象的本地副本。调用
foo
不会修改
main
中的本地变量
kk