gpt4 book ai didi

c++ - 为什么在初始化此类时不调用列表初始化?

转载 作者:行者123 更新时间:2023-12-03 06:53:54 25 4
gpt4 key购买 nike

根据本页描述的值初始化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.

所以我期待在下面的代码片段中初始化类时将调用 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 。所以值初始化的效果应该是:

  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选择了已删除的默认构造函数,程序格式错误。

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

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 因为其他用户声明的构造函数)。那么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

关于c++ - 为什么在初始化此类时不调用列表初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64367019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com