wai*_*r92 2 c++ lambda reference
有什么区别f1和f2?
void foo(const std::string& test){
auto f1 = [&test](){
std::cout << test << std::endl;
};
f1();
auto f2 = [test](){
std::cout << test << std::endl;
};
f2();
}
int main()
{
std::string x = "x";
foo(x);
}
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,testlambda内的变量类型均为std::string const&,但这是否真的一样?
f1和f2有什么区别?
是。
真的一样吗?
号f2捕获一个std::string const。
lambda捕获的类型推导与auto声明相同:
[&test](){} // a reference
[ test](){} // an object
auto &var = test; // a reference
auto var = test; // an object
std::string &var = test; // a reference
std::string var = test; // an object
template<class T> void foo1(T& var);
template<class T> void foo2(T var);
foo1(test); // a reference
foo2(test); // an object
Run Code Online (Sandbox Code Playgroud)