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;
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;
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
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!