C ++. Default initialization, copy initialization, and default initialization.

From the book "C ++ Programming Language", 4th edition, Section "17.3.1 Initialization without Constructors", Page 489

The marked line in the example from the book does not compile with this error -

$ g++ -std=c++11 ch17_pg489.cpp
ch17_pg489.cpp: In function 'int main()':
ch17_pg489.cpp:32:34: error: could not convert 's9' from 'Work' to 'std::string {aka std::basic_string<char>}'
      Work currently_playing { s9 }; // copy initialization

I have cygwin

$ g++ --version
g++.exe (tdm64-2) 4.8.1

To quote the text from the above section,

we can initialize objects of a class for which we have not defined a constructor using
β€’ memberwise initialization,
β€’ copy initialization, or
β€’ default initialization (without an initializer or with an empty initializer list).


#include <iostream>

struct Work {
    std::string author;
    std::string name;
    int year;
};

int main() {

    Work s9 { "Beethoven",
    "Symphony No. 9 in D minor, Op. 125; Choral",
    1824
    }; //memberwise initialization

/* 
    // This correctly prints the respective fields
    std::cout << s9.author << " | " 
                        << s9.name << " | "
                        << s9.year << std::endl;
*/

  // Fails to compile
    Work currently_playing { s9 }; // copy initialization

    Work none {}; // default initialization

    return 0;
}

According to my understanding, any copy initialization will be provided by the default copy constructor generated by the compiler. Or it will be just a wise copy of the member (assigning one structure to another, as in C). Therefore, the program should have been compiled here.

Or is it a quirk compiler ??

Any explanation?

+4
1

4-

http://www.stroustrup.com/4th.html

, {} :

X x1 {2};     // construct from integer (assume suitable constructor)
X x2 {x1};        // copy construction: fails on GCC 4.8 and Clang 3.2

. . ++ 14. :

X x3(x1);     // copy construction
X x4 = x1;        // copy construction

GCC 4.10

.

+3

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


All Articles