[英]why is list initialization not invoked when initialize this class?
according to value initialization described in this pagehttps://en.cppreference.com/w/cpp/language/value_initialization根据本页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.
如果 T 是一个没有默认构造函数但有一个采用 std::initializer_list 的构造函数的类类型,则执行列表初始化。
so I was expecting when initialize the class in bellow code snippet will invoke Myclass(const std::initializer_list<int> &l)
, but the compiler says所以我期待在下面的代码片段中初始化类时会调用
Myclass(const std::initializer_list<int> &l)
,但编译器说
> the default constructor of "Myclass" cannot be referenced -- it is a deleted function
why is that?这是为什么? this is the code, I compiled with Mingw64 C++11 on windows.
这是代码,我在 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
does have a default constructor; Myclass
确实有一个默认构造函数; which is just marked as delete
explicitly.这只是明确标记为
delete
。 So the effect of value-initialization should be:所以值初始化的效果应该是:
- if T is a class type with no default constructor or with a user-provided or deleted default constructor, the object is default-initialized ;
如果 T 是没有默认构造函数或具有用户提供或删除的默认构造函数的类类型,则该对象是默认初始化的;
In default-initialization the deleted default constructor is selected and the program is ill-formed.在默认初始化中,删除的默认构造函数被选中并且程序格式错误。
If not to declare the default constructor as如果不将默认构造函数声明为
class Myclass {
public:
// Myclass() = delete;
Myclass(Myclass &&m) {}
Myclass(const Myclass &m) {}
Myclass(const std::initializer_list<int> &l) { std::cout << "initializer list"; }
};
Then Myclass
doesn't have default constructor;然后
Myclass
没有默认构造函数; (and no implicitly-declared default constructor because of other user-declared constructors). (并且没有隐式声明的默认构造函数,因为其他用户声明的构造函数)。 Then list-initialization is performed (as you expected), as the effect
然后执行 列表初始化(如您所料),效果如下
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 typestd::initializer_list
所有采用
std::initializer_list
作为唯一参数的构造函数,或者如果其余参数具有默认值,则作为第一个参数,都被检查,并通过 重载决议与std::initializer_list
类型的单个参数匹配
Checkout this post .结帐这篇文章。 in a nutshell:
简而言之:
Myclass() = delete;
Myclass() = delete;
line, it will choose the best constructor, aka your initialized_list
one.initialized_list
一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.