Lvalue initialization fails

Some code samples from "C ++ 4th Edition Programming Language" make me confused. Here are my test cases.

Env gcc version 4.6.3 (Debian 4.6.3-14 + rpi1) with -std = C ++ 0x

  • Code1 string var {"Cambridge"}; string& r1 {var}; string var {"Cambridge"}; string& r1 {var}; Fail compilation
  • Code2 string var {"Cambridge"}; string& r1 = var; string var {"Cambridge"}; string& r1 = var; Successful compilation
  • Code3 string var {"Cambridge"}; string&& r1 {var}; string var {"Cambridge"}; string&& r1 {var}; Successful compilation
  • Compilation of Code1 failed with g++ -g -DLINUX -std=c++0x -c src/dummy.cpp -o src/dummy.o src/dummy.cpp: In function 'int main(int, char**)': src/dummy.cpp:26:17: error: invalid initialization of non-const reference of type 'std::string& {aka std::basic_string<char>&}' from an rvalue of type '<brace-enclosed initializer list>' make: *** [src/dummy.o] Error 1
  • Code1 must be in order according to the books. Section 7.7.2, since var is an lvalue, but why does code1 not work, but code3 works in my situation?
+6
source share
1 answer

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.

+3
source

Source: https://habr.com/ru/post/955827/


All Articles