Home >Backend Development >C++ >When Can an Rvalue Reference Parameter Bind to an Lvalue Argument in C ?

When Can an Rvalue Reference Parameter Bind to an Lvalue Argument in C ?

Linda Hamilton
Linda HamiltonOriginal
2024-12-07 21:48:18885browse

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(t).

The Relevant Rules:

  • An implicit move to an rvalue reference parameter occurs when returning a named value from a function, or when the value does not have a name.
  • Only rvalue references and const& can bind to rvalues.
  • Rvalue references and const& undergo lifetime extension when directly bound to a reference outside of a constructor.
  • Reference collapsing transforms T&& into X& or X const& if T is of type X& or X const&.
  • In type deduction contexts, T&& deduces T as X, X&, X const&, or X const&& based on the argument type.

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!

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