【问题标题】:C++11 - lambda function pass vector in capture and modify itC ++ 11 - lambda函数在捕获中传递向量并对其进行修改
【发布时间】:2017-11-30 17:17:52
【问题描述】:

我有这个代码:

#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;
}

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

我收到了这个错误:

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

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

【问题讨论】:

    标签: c++11 lambda


    【解决方案1】:

    默认情况下,闭包类型将其operator() 声明为const 限定的成员函数。这意味着无法在 lambda 中修改由副本捕获的对象。要使 operator() 成为非 const 成员函数,您必须标记 lambda mutable

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

    [Live example]

    (我还冒昧地删除了声明中的双精度类型说明)。

    当然,请记住,在捕获中创建的kk 副本是 lambda 对象的本地副本。 main中的局部变量kk不会被foo修改。

    【讨论】:

      猜你喜欢
      • 2013-07-16
      • 2015-06-13
      • 2023-04-05
      • 2021-02-07
      • 1970-01-01
      • 2011-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多