【发布时间】: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 并且向量将不再可用,它将超出范围。
【问题讨论】: