Understanding Rvalue Reference Variables
In C , rvalue references are a specialized type of reference that can only bind to rvalues (values with no name). However, a surprising behavior arises when a function is overloaded with both an lvalue reference and an rvalue reference overload.
Confusion: Rvalue Reference Variables Behaving Like Lvalues
Consider the following function overloads:
void f(T&&); // Overload #1 (rvalue reference) void f(T&); // Overload #2 (lvalue reference)
Within another function:
void g(T&& t) { f(t); // Calls Overload #2 (lvalue reference) }
The surprising result is that Overload #2 (lvalue reference) is called, even though the argument t is an rvalue reference.
Reason: Rvalue References Are Lvalues with a Special Type
Rvalue references are considered lvalues because they have a name and can be used as an lvalue for most purposes. However, their type, rvalue reference, specifies their limited binding capabilities.
How to Invoke the Rvalue Reference Overload
To invoke the rvalue reference overload, the argument must be explicitly converted to an rvalue reference using the static_cast operator:
f(static_cast<T&&>(t));
Other Rules Governing Rvalue References
The above is the detailed content of Why Does an Rvalue Reference Sometimes Act Like an Lvalue in C Function Overloading?. For more information, please follow other related articles on the PHP Chinese website!