Home >Backend Development >C++ >Why Can\'t Non-Const Lvalue References Bind to Dissimilar Types in C ?

Why Can\'t Non-Const Lvalue References Bind to Dissimilar Types in C ?

Susan Sarandon
Susan SarandonOriginal
2024-12-03 00:14:11974browse

Why Can't Non-Const Lvalue References Bind to Dissimilar Types in C  ?

Binding Non-const lvalue References to Dissimilar Types

In C , a non-const lvalue reference must bind to an lvalue of the same type. This can be confusing when attempting to bind a temporary object to a non-const reference, as demonstrated in the following example:

int a;
const double &m = a; // This is allowed
double &m = a; // This produces an error

The error, "non-const lvalue reference to type 'double' cannot bind to a value of unrelated type 'int'," indicates that a reference of a non-const type cannot bind to an object of a different type.

The reason for this restriction is that a temporary object cannot be bound to a non-const reference. When a is converted to double, a temporary object is created. As a result, the following line of code:

double &m = a;

Attempts to bind a non-const reference to a temporary object, which is not permitted.

However, there is an exception to this rule in Visual Studio, where a compiler extension allows binding non-const references to temporary objects. However, this behavior is not standard and will result in an error in other compilers like GCC.

The above is the detailed content of Why Can\'t Non-Const Lvalue References Bind to Dissimilar Types 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