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