It fails because it tries to bind the value of r to a nonconst lvalue reference.
8.5.4 Initializing a List
[# 3]
- Otherwise, if T is a reference type, the prvalue of the temporary type is the reference to T is initialized by the list, and the link is associated with this temporary . [Note. As usual, the binding will fail and the program will be poorly formed if the reference type is a lvalue reference to a non-constant type. - final note]
Check this example to make sure r1 attached to a single object
#include <string> #include <iostream> int main () { std::string var {"Cambridge"}; const std::string& r1 {var}; const std::string& r2 (var); var.clear (); std::cout << "var = " << var << std::endl; std::cout << "r1 = " << r1 << std::endl; std::cout << "r2 = " << r2 << std::endl; }
and compare this to r2 .
PS. The question arises why the following statement is not canceled in accordance with the above considerations:
int x; int &y { x };
the standard says (in the same place as above, but the following sentence):
- Otherwise, if there is one element in the initialization list, the object or link is initialized from this element;
The link is explicitly mentioned in this section, in other words, the initialization of the link is not described in one sentence, but there are several possibilities (perhaps in the order of things) ?, which explains why int & behaves in this way.
source share