简体   繁体   English

作为参数的空初始化列表不调用默认构造函数

[英]Empty initializer list as argument doesn't call default constructor

The following code 以下代码

class A {
public:
    A() {} // default constructor
    A(int i) {} // second constructor
};
int main() {
    A obj({});
}

calls the second constructor. 调用第二个构造函数。 Probably the empty initializer_list is treated as one argument and is converted to int . 可能将空的initializer_list视为一个参数并转换为int But when you remove the second constructor from the class, it calls the default constructor. 但是当你从类中删除第二个构造函数时,它会调用默认的构造函数。 Why? 为什么?

Also, I understand why A obj { {} } will always call a constructor with one argument as there we are passing one argument which is an empty initializer_list . 另外,我理解为什么A obj { {} }总是会调用带有一个参数的构造函数,因为我们传递的是一个空的initializer_list参数。

The presence of the parentheses surrounding the braces in A obj({}); A obj({});括号周围括号的存在A obj({}); indicates the single argument constructor will be called, if possible. 表示如果可能,将调用单个参数构造函数。 In this case it is possible because an empty initializer list, or braced-init-list , can be used to value initialize an int , so the single argument constructor is called with i=0 . 在这种情况下,有可能因为空初始化列表或braced-init-list可用于初始化int值,因此使用i=0调用单个参数构造函数。

When you remove the single argument constructor, A obj({}); 当你删除单个参数构造函数时, A obj({}); can no longer call the default constructor. 不能再调用默认构造函数。 However, the {} can be used to default construct an A and then the copy constructor can be called to initialize obj . 但是, {}可用于默认构造A ,然后可以调用复制构造函数来初始化obj You can confirm this by adding A(const A&) = delete; 您可以通过添加A(const A&) = delete;来确认这一点A(const A&) = delete; , and the code will fail to compile. ,代码将无法编译。

It's because the {} in A obj({}); 这是因为{}中的A obj({}); ends up being interpreted as of type int . 最终被解释为int类型。 So the code ends up being similar to A obj(0); 所以代码最终类似于A obj(0); .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 具有默认参数的initializer_list构造函数 - initializer_list constructor with default argument 空括号调用默认构造函数或构造函数采用std :: initializer_list吗? - Do empty braces call the default constructor or the constructor taking an std::initializer_list? 构造函数初始化列表不遵循顺序 - Constructor initializer list doesn't follow order 构造函数初始值设定项列表中的共享参数 - Shared argument in constructor initializer list 启用默认初始化列表构造函数 - Enable default initializer list constructor 具有默认构造函数的对象的初始化列表 - Initializer list for objects with default constructor 区分具有默认参数值的构造函数和空参数列表 - Differentiate between constructor with default argument value and empty argument list 类的Ctor初始化程序不会调用适当的构造函数 - Ctor-initializer for a class doesn't call to the appropriate constructor 为什么带有支撑初始化列表的Constructor / virtual析构函数不起作用? - Why doesn't Constructor/virtual destructor with braced initializer list work? std :: list <std :: unique_ptr>:空的初始化列表与默认构造函数 - std::list<std::unique_ptr>: empty initializer list vs. default constructor
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM