Reputation:
Is there any difference between f1
and 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);
}
It looks like in both cases, the type of the test
variable inside of the lambda will be std::string const&
, but is it really the same?
Upvotes: 4
Views: 1615
Reputation: 238321
Is there any difference between f1 and f2?
Yes.
but is it realy the same?
No. f2
captures a std::string const
.
Type deduction of lambda captures works the same as auto
declarations:
[&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
Upvotes: 8