【问题标题】:C++ Member-wise initialization, copy initialization and default initializationC++ 成员初始化、复制初始化和默认初始化
【发布时间】:2014-05-29 01:22:30
【问题描述】:

摘自《The C++ Programming Language, 4th edition》一书, 第 489 页的“17.3.1 没有构造函数的初始化”部分

书中示例中的标记行无法编译并出现此错误 -

$ 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, 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;
}

根据我的理解,复制初始化将由编译器生成的默认复制构造函数提供,或者它只是一个成员明智的复制(将一个结构分配给另一个,如在 C 中)。所以程序应该已经编译到这里了。

或者这是编译器的怪癖??

有什么解释吗?

【问题讨论】:

    标签: c++ compilation compiler-errors initialization


    【解决方案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
    

    我知道。这是标准中的错误。已为 C++14 修复。现在使用 传统符号之一:

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

    这是 GCC 4.10 的 fixed

    Here's 缺陷报告本身。

    【讨论】:

    • 大声笑。在发布问题之前,我已经访问了该站点的勘误表页面。还看到了您在这里粘贴的内容。仍然我的眼睛没有选择这一行 - “//复制构造:在 GCC 4.8 和 Clang 3.2 上失败”.. 看到我什至在问题中给出了我的编译器版本 :) 感谢您提供有关 GCC 4.10 中修复的附加信息..事实上,它是一个编译器怪癖。
    • @nightlytrails 这是标准的缺陷,而不是编译器。
    • 再一次,勘误表中明确提到了“标准中的错误”。大概是时候让我小睡一下,让我疲惫的眼睛休息一下了 :-)
    • @nightlytrails 不用担心,每个人都会遇到。
    猜你喜欢
    • 2015-03-22
    • 2020-02-08
    • 2019-09-10
    • 2014-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    相关资源
    最近更新 更多