Home > Backend Development > C++ > Why Can\'t Non-Const References Bind to Unrelated Lvalues or Temporaries in C ?

Why Can\'t Non-Const References Bind to Unrelated Lvalues or Temporaries in C ?

Mary-Kate Olsen
Release: 2024-11-25 22:17:11
Original
468 people have browsed it

Why Can't Non-Const References Bind to Unrelated Lvalues or Temporaries in C  ?

Non-const Reference Binding Restrictions

In C , const references can bind to lvalues of both the same type and unrelated types. However, non-const references face additional restrictions when binding to lvalues.

Unrelated Lvalue Binding Failure

Consider the following code:

int a;
double &m = a; // error: non-const lvalue reference to type 'double' cannot bind to a value of unrelated type 'int'
Copy after login

Here, the non-const reference m is attempted to be bound to an lvalue of type int. This fails because non-const references cannot bind to unrelated lvalues.

Temporary Object Binding Prohibition

Non-const references also cannot bind to temporary objects. For example:

double &m = a; // compilation error: temporary bound to non-const reference
Copy after login

In this case, the assignment of a to m involves converting an int to a double and creating a temporary object. Non-const references cannot bind to such temporary objects.

The rationale behind this restriction is that non-const references require access to the original object's address, which is not possible for temporary objects since they are destroyed immediately after use.

Visual Studio Compiler Extension

It's important to note that in Visual Studio, this error may not occur due to a compiler extension that allows binding to temporary objects in certain cases. However, other compilers like GCC will strictly enforce the non-binding rule.

The above is the detailed content of Why Can\'t Non-Const References Bind to Unrelated Lvalues or Temporaries in C ?. 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