为什么在初始化这个 class 时不调用列表初始化?

why is list initialization not invoked when initialize this class?

根据本页描述的值初始化https://en.cppreference.com/w/cpp/language/value_initialization

If T is a class type that has no default constructor but has a constructor taking std::initializer_list, list-initialization is performed.

所以我期待在下面的代码片段中初始化 class 时会调用 Myclass(const std::initializer_list<int> &l) ,但是编译器说

> the default constructor of "Myclass" cannot be referenced -- it is a deleted function

这是为什么?这是代码,我在 windows.

上用 Mingw64 C++11 编译
#include <iostream>
class Myclass {
    public:
     Myclass() = delete;
     Myclass(Myclass &&m) {}
     Myclass(const Myclass &m) {}
     Myclass(const std::initializer_list<int> &l) { std::cout << "initializer list"; }
};
int main(int argc, char const *argv[]) {
    Myclass m2 {};
     Myclass m1={};
}

结帐。简而言之:

  • 如果显式删除了默认构造函数,编译器将假定不存在任何默认构造函数
  • 但是,如果您删除 Myclass() = delete; 行,它将选择最佳构造函数,也就是您的 initialized_list 构造函数。

Myclass 确实有默认构造函数;这只是明确标记为 delete 。所以value-initialization的效果应该是:

  1. if T is a class type with no default constructor or with a user-provided or deleted default constructor, the object is default-initialized;

default-initialization中选择删除的默认构造函数,程序为ill-formed.

如果不声明默认构造函数为

class Myclass {
    public:
     // Myclass() = delete;
     Myclass(Myclass &&m) {}
     Myclass(const Myclass &m) {}
     Myclass(const std::initializer_list<int> &l) { std::cout << "initializer list"; }
};

那么Myclass没有默认构造函数; (并且没有执行 implicitly-declared default constructor because of other user-declared constructors). Then list-initialization(如您所料),因为效果

All constructors that take std::initializer_list as the only argument, or as the first argument if the remaining arguments have default values, are examined, and matched by overload resolution against a single argument of type std::initializer_list