Home >Backend Development >C++ >Why Doesn't `T&&` Always Behave Like a True Rvalue Reference?

Why Doesn't `T&&` Always Behave Like a True Rvalue Reference?

Linda Hamilton
Linda HamiltonOriginal
2024-11-30 06:21:15398browse

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(t)) is necessary to invoke the rvalue reference overload f(T&&).

To summarize, the C rules governing this behavior are:

  • Implicit moves occur when returning named values from functions, when values have no names, or when functions explicitly return rvalue references.
  • Only rvalue references and const& can bind to rvalues.
  • Reference lifetime extension on temporary values occurs when directly bound to a reference outside of a constructor and applies to rvalue references and const&.
  • T&& is not always an rvalue reference; it may collapse to X&, X const&, or X const&& based on the type of T.
  • T&& can act as a "forwarding reference" in type deduction contexts, deducing T based on the type of the argument.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn