[英]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.