Home > Backend Development > C++ > Why Doesn't `f(T&&)` Get Called When Passing an Rvalue Reference to It?

Why Doesn't `f(T&&)` Get Called When Passing an Rvalue Reference to It?

Mary-Kate Olsen
Release: 2024-12-08 13:17:11
Original
165 people have browsed it

Why Doesn't `f(T&&)` Get Called When Passing an Rvalue Reference to It?

Why rvalue References Variables are Not rvalue References

Consider two overloads of a function f:

void f(T&&&); // #1
void f(T&);  // #2
Copy after login

In another function g:

void g(T&& t) 
{ 
  f(t);  // calls #2
}
Copy after login

Why does the overload f(T&) get called despite the parameter t being an rvalue?

The Nature of rvalue References

Rvalue references are variables that can only bind to rvalues (objects without names). T&&t has a name, making it an lvalue.

Distinction between Type and Value

T&& is the type rvalue reference. An rvalue reference can bind only to rvalues, but it is otherwise an lvalue of reference type.

Special Cases

  • static_cast(t): This explicitly creates an rvalue reference, enabling the call to f(T&&).

Rules Governing Rvalue References

  • Implicit moves occur when returning named values from functions or when values have no names.
  • Rvalue references or const& can only bind to rvalues.
  • Reference lifetime extension applies to temporaries bound to references outside constructors.
  • In certain contexts, T&& collapses to X& or X const& if T is X& or X const&.
  • T&& can act as a "forwarding reference" in type deduction.

The above is the detailed content of Why Doesn't `f(T&&)` Get Called When Passing an Rvalue Reference to It?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template