使用统一初始化调用复制构造函数

calling copy constructor with uniform initialization

我正在尝试调用具有统一初始化的默认复制构造函数,但它不起作用。

例如:

#include <string>

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
        Work currently_playing {s9};    // copy initialization

        return 0;
}

我将其编译为:g++ -std=c++11 -c Ex1.cpp

编译器报错:

Ex1.cpp: In function ‘int main()’:
Ex1.cpp:11:28: error: could not convert ‘s9’ from ‘Work’ to ‘std::string {aka std::basic_string<char>}’
  Work currently_playing {s9}; // copy initialization
                            ^

统一初始化不能复制初始化对象吗?

这是旧的 g++ 错误或旧的核心语言缺陷。您的代码从 g++ 5 开始正确编译。我强烈建议您更新您的编译器,因为 4.8 非常旧。

conformance view on godbolt.org

live example on wandbox

这是 C++11 标准中的错误。 C++14 更改了 list-initialization 的执行方式。在 C++11 中,如果 Xaggregate typeX{X{}} 将执行 聚合初始化。 C++14 添加了一个额外的子句,以便此代码正确调用相应的构造函数; [dcl.init.list]/3.2:

If T is an aggregate class and the initializer list has a single element of type cv U, where U is T or a class derived from T, the object is initialized from that element (by copy-initialization for copy-list-initialization, or by direct-initialization for direct-list-initialization).

来源:

http://eel.is/c++draft/dcl.init.list#3.2

http://en.cppreference.com/w/cpp/language/list_initialization#Explanation