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

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

Patricia Arquette
Release: 2024-12-06 14:20:13
Original
1011 people have browsed it

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

Non-const Lvalue References and Temporary Bindings

In C , non-const lvalue references are expected to bind to lvalues of the same or derived type. However, certain situations, such as binding to temporary objects, can lead to errors.

Why is the following code valid?

int a;
const double &m = a;
Copy after login

In this case, a reference is bound to an lvalue, and since the reference is const, the lvalue cannot be modified. This is allowed in C as long as the types are compatible.

However, when trying to bind a non-const lvalue reference to an lvalue of a different type, an error occurs:

int a;
double &m = a;
Copy after login

error: non-const lvalue reference to type 'double' cannot bind to a value of unrelated type 'int'

This error is raised because a temporary is involved. The implicit type conversion from int to double creates a temporary object. Non-const references cannot be bound to temporary objects because they require the object to have a known lifetime and location. Temporary objects, by their nature, exist for a limited duration.

Visual Studio may compile this code without errors due to a compiler extension that allows binding to temporaries in certain cases. However, compilers like GCC will correctly flag this error.

The example below demonstrates a similar issue with user-defined types:

struct Foo {};

Foo &obj = Foo(); // error: binding non-const reference to temporary
Copy after login

Understanding this concept is crucial for proper reference handling in C and avoiding runtime issues related to object lifetime.

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