I can't do this:
int &&q = 7;
int &&r = q;
//Error Message:
//cannot convert from 'int' to 'int &&'
//You cannot bind an lvalue to an rvalue reference
If I understand correctly, when initializing an rvalue reference, there's a temporary variable got initialized too. So int &&q = 7;
can be considered as:
int temp = 7;
int &&q = temp;
And when using a reference on the right side, I am actually using the referee. So int &&r = q;
can be considered as:
int &&r = temp; //bind an lvalue to an rvalue reference, cause error, understandable
So above is how I understand the compiler error occurs.
Why adding std::forward
can solve that?
int &&q = 7;
int &&r = std::forward<int>(q);
I know the std::forward
always returns an rvalue reference, how is the reference returned by std::forward
different from int&&q
?
int &&r = std::move(q);
would be the more idiomatic way to do the cast in this case.std::forward
is meant for use in "perfect forwarding" to pass on parameters which have template types such astemplate <typename T> void f(T&& x)
ortemplate <typename... T> void f(T&&... x)
– Brassiedecltype(q)
is equivalent toint&&
whiledecltype((q))
is equivalent toint&
– Brassie