Home >Backend Development >C++ >Why Doesn't `T&&` Always Behave Like a True Rvalue Reference?
Why Does T&& Not Behave Like an Rvalue Reference?
When working with function overloads like void f(T&&) and void f(T&), it's surprising to find that f(T&) is called when passing in T&&, even though the reverse is not true. This is due to the behavior of rvalue references in C .
Contrary to intuition, T&& is not simply an rvalue reference. It's the type rvalue reference, which means it can only bind to rvalues but otherwise behaves like an lvalue of type rvalue reference. This binding behavior ensures that objects without names and those about to lose their names are automatically treated as rvalues.
However, since T&& has a name (i.e., t), it's considered an lvalue and thus calls the f(T&) overload. Static casting t to T&&& using f(static_cast
To summarize, the C rules governing this behavior are:
The above is the detailed content of Why Doesn't `T&&` Always Behave Like a True Rvalue Reference?. For more information, please follow other related articles on the PHP Chinese website!