I'm reading the part of the Standard about initializing an lvalue reference from an rvalue (https://eel.is/c++draft/dcl.init.ref#5.3 ). I know a reference to const is required in this scenario, but I cannot find out where the const is mandated in the Standard text. Take the first initialization in Example 5 of the webpage as an example with const removed:
1 2 3 4
struct A { };
struct B : A { } b;
extern B f();
/*const*/ A& rca2 = f(); //I purposely remove const
Here I purposely remove the const qualifier in the declaration of rca2. Next I will show my analysis according to the Standard text. Here the initializer f() is an rvalue, so we jump to (5.3). “cv1 T1” is "A" while “cv2 T2” is "B". I think “cv1 T1” is reference-compatible with “cv2 T2” because a pointer to B can be converted to a pointer to A via a standard conversion. As a result, conditions in (5.3.1) are all satisfied. Converted initializer f() is a prvalue, whose type is B (T4 in the Standard text (5.3)). Now “cv1 T4” is B, from which we apply the temporary materialization conversion, resulting in a glvalue whose type is still B. Then the lvalue reference rca2 is bound to this glvalue result of type B.
There must be somewhere I made a mistake in the above analysis because an error is issued if I omit the const qualifier. But I don't know where it is that const is mandated. Please point out that to me. Thank you.
I don't think I've ever actually read the standard in over 30 years of using c++!
Put simply you can't initialise a ref from a rvalue as the rvalue doesn't 'exist' past the statement (rvalue life expires). However with a const ref, rvalue 'life' is extended to the life of the const ref.