Please consider the following code:
class a {
public:
int a;
};
void func1( a &&var1 );
void func2( a &&var2 )
{
func1(var2);
}
When trying to compile it, gcc returns the following:
question.cpp: In function ‘void func2(a&&)’:
question.cpp:10:14: error: cannot bind ‘a’ lvalue to ‘a&&’
func1(var);
^
question.cpp:6:6: error: initializing argument 1 of ‘void func1(a&&)’
void func1( a &&var );
^
It seems that var2 is an lvalue, despite it being quite explicitly defined as an rvalue reference. Does the double ampersands lose their meaning once assigned? What is the mechanism that's at work here?
Inside the function implementation, the once-rvalue becomes a regular variable (l-value), to which you can make assignments. If you want to turn it into an rvalue again, you must use std::move, as in:
void func2( a &&var2 ) {
func1(std::move(var2));
}
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