C++11 - 捕获中的 lambda 函数传递向量并修改它

Mar*_*key 6 lambda c++11

我有这个代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

为什么我不能kk在 lambda 函数内部修改通过捕获传递的vector ?

我收到此错误:

11:21:错误:将 'const std::vector' 作为 'void std::vector<_Tp, _Alloc>::push_back(std::vector<_Tp, _Alloc>::value_type&&) [with _Tp = 整数;_Alloc = std::allocator; std::vector<_Tp, _Alloc>::value_type = int]' 丢弃限定符 [-fpermissive]

我可以通过引用传递它,但问题是,如果从线程调用我的 lambda 并且向量将不再可用,它将超出范围。

Rei*_*ica 5

默认情况下,闭包类型将其声明operator()const-qualified 成员函数。这意味着无法在 lambda 内修改通过复制捕获的对象。要使operator()const成员函数,您必须标记 lambda mutable

std::function<int(int)> foo{[kk](int x) mutable
{
    kk.push_back(1);
    return kk[0]+1;
}};
Run Code Online (Sandbox Code Playgroud)

[活生生的例子]

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

当然,请记住,kk捕获中的made副本是 lambda 对象的本地副本。局部变量kkinmain不会被调用修改foo