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
T is int& so t1 should be int&
References are not pointers. T
may be deduced as int&
, thus t1
is a reference. But you asked the lambda to capture t1
by value. That means copying the value referenced by t1
.
If t1
were 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With