When I capture a value but the value type is a reference in a template function
template<class T>
void test(T&&i)
{
++i;
std::cout << i << std::endl;
}
template<class T>
void typetest(T&& t)
{
++t;
T t1(t);
[=]() mutable { std::cout << t1 << std::endl; return test(t1); }();
std::cout << t << std::endl;
}
int main()
{
int i=1;
typetest(i);
}
it prints
2
3
2
But in T t1(t); T is int& so t1 should be int& when the lambda calls test(t1). Why is the output not
2
3
3
References are not pointers.
Tmay be deduced asint&, thust1is a reference. But you asked the lambda to capturet1by value. That means copying the value referenced byt1.If
t1were a pointer, you would get the pointer by value. But you can’t get a reference “by value”; you can only get the value being referenced.