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);
}
看起来在这两种情况下,lambda 内部的 test
变量的类型都是 std::string const&
,但它真的一样吗?
最佳答案
Is there any difference between f1 and f2?
是的。
but is it realy the same?
没有。 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
关于c++ - 通过引用传递对 lambda 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55244833/