Home >Backend Development >C++ >When Can an Rvalue Reference Parameter Bind to an Lvalue Argument in C ?
Why an Rvalue Reference Parameter Can Bind to an Lvalue Argument
In C , rvalue references are expected to be bound to rvalues. However, there are cases where an rvalue reference parameter can match an lvalue argument, surprising many programmers.
Consider the following code:
void f(T&&); // #1 void f(T&); // #2
Normally, we would expect the f(T&&) overload to be called when passing an rvalue, and f(T&) overload for lvalues. However, the behavior is different:
void g(T&& t) { f(t); // calls #2 }
In this example, the f(T&) overload is called even though t is an rvalue. This happens because, despite its rvalue reference type, t is still considered an lvalue.
The Rationale:
Rvalues are typically entities without names or those that will lose their names shortly. Rvalue references can only bind to rvalues. However, t has a name, and its lifetime will not expire immediately.
The Type T&&:
T&& is the type of an rvalue reference. While it can only bind to rvalues, it otherwise behaves as an lvalue of type rvalue reference. Its rvalue reference nature matters only during its construction and when performing decltype(variable_name).
The Role of std::move():
std::move() returns an rvalue reference by performing a static_cast
The Relevant Rules:
The above is the detailed content of When Can an Rvalue Reference Parameter Bind to an Lvalue Argument in C ?. For more information, please follow other related articles on the PHP Chinese website!