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

4

来自《C++编程语言》第四版的17.3.1节“不需要构造函数的初始化”,第489页。

书中示例中的标记行无法编译,会出现以下错误 -

$ 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

我有Cygwin

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

引用上述部分的文本,如下所示:

we can initialize objects of a class for which we have not defined a constructor using
• memberwise initialization,
• copy initialization, ordefault 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;
}

据我的理解,编译器生成的默认复制构造函数提供了复制初始化方法,或者仅仅是成员逐一复制(像C语言中一样将一个结构体赋值给另一个结构体)。因此,程序应该能够编译通过。这是编译器的问题吗?有任何解释吗?
1个回答

3
正如您在第四版勘误表中所看到的。

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. For now use one of the traditional notations:

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

这是针对GCC 4.10的修正

以下是缺陷报告本身。


哈哈,我在发布问题之前已经访问了该网站的勘误页面。我也看到了你在这里粘贴的内容。但是我的眼睛仍然没有注意到这一行 - "// copy construction: fails on GCC 4.8 and Clang 3.2" .. 你看,我甚至在问题中提供了我的编译器版本 :) 感谢你提供有关GCC 4.10修复的额外信息..确实是编译器的小问题。 - nightlytrails
@nightlytrails 这是标准的缺陷,而不是编译器的问题。 - user657267
再次提醒,这个“标准中的bug”已经在勘误表中明确提到。也许是时候我该小睡一会儿,让疲惫的眼睛得到休息 :-) - nightlytrails
@nightlytrails 不用担心,这种事情每个人都会遇到的。 - user657267

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接