简体   繁体   English

C ++成员初始化,复制初始化和默认初始化

[英]C++ Member-wise initialization, copy initialization and default initialization

From the book, The C++ Programming Language, 4th edition, Section "17.3.1 Initialization Without Constructors", Page 489 从本书,C ++编程语言,第4版,第17.3.1节“没有构造函数的初始化”,第489页

The marked line in the example from the book fails to 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 我有Cygwin

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

To quote from the text from the aforementioned 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;
}

As per my understanding, either copy initialization would be provided by the default copy constructor generated by the compiler Or it would be simply a member wise copy (assigning one struct to another, as in C). 根据我的理解,复制初始化将由编译器生成的默认复制构造函数提供,或者它只是一个成员明智的复制(将一个结构分配给另一个,如在C中)。 So the program should have compiled here. 所以程序应该在这里编译。

Or is this the compiler quirk?? 或者这是编译器的怪癖?

Any explanations ? 有什么解释吗?

As you can see under the errata for the 4th edition 正如您在第4版的勘误表中看到的那样

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

People have pointed out that the {} doesn't work for copy construction: 人们已经指出{}不适用于复制构造:

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

I know that. 我知道。 It's a bug in the standard. 这是标准中的一个错误。 Fixed for C++14. 修复了C ++ 14。 For now use one of the traditional notations: 现在使用其中一种传统符号:

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

It's fixed for GCC 4.10 它是固定的GCC 4.10

Here's the defect report itself. 这是缺陷报告本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM