默认初始化显式构造函数 c++
如果默认构造函数是显式的,那么 C++11 中的默认初始化如何工作?例如:
#include <iostream>
struct Foo {
int x;
explicit Foo(int y = 7) : x{y} {}
}
int main() {
Foo foo;
std::cout << foo.x << std::endl;
}
在main中,变量foo
被默认初始化。根据我的理解,这将调用默认构造函数(如果存在)。否则,不会发生初始化,foo
包含不确定的值,并且打印 foo.x
是未定义的行为。
Foo
有一个默认构造函数,但它是显式的。该构造函数是否保证被调用,或者程序的最后一行是未定义的行为?
How does default initialization work in C++11 if the default constructor is explicit? For example:
#include <iostream>
struct Foo {
int x;
explicit Foo(int y = 7) : x{y} {}
}
int main() {
Foo foo;
std::cout << foo.x << std::endl;
}
In main, the variable foo
is default initialized. Based on my understanding, this will call a default constructor, if one exists. Otherwise, no initialization occurs, foo
contains indeterminate values, and printing foo.x
is undefined behavior.
There is a default constructor for Foo
, but it is explicit. Is that constructor guaranteed to be called, or is the last line of the program undefined behavior?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的使用没问题。可能发生的最糟糕的事情是编译器将无法使用构造函数,因为它是显式的并且无法编译。但是,定义一个变量将正确调用
显式
默认构造函数。对默认构造函数使用
显式
可以防止如下使用:Your use is okay. The worst thing that could happen would be that the compiler would not be able to use the constructor since it is explicit and fail to compile. However, defining a variable as you have will correctly call the
explicit
default constructor.The use of
explicit
for a default constructor prevents uses like the following: