POD 与非 POD 类类型的默认初始化
C++ 标准表示 (8.5/5):
默认初始化
T
类型的对象意味着:
如果
T
是非 POD 类类型(第 9 条),则调用T
的默认构造函数(如果T
没有 可访问的默认构造函数)。如果
T
是数组类型,则每个元素都默认初始化。否则,该对象将被零初始化。
使用此代码,
struct Int { int i; };
int main()
{
Int a;
}
对象 a
被默认初始化,但显然 ai
不一定等于 0 。这是否与标准相矛盾,因为 Int
是 POD 而不是数组?
编辑从class
更改为struct
,以便Int
是一个POD。
The C++ standard says (8.5/5):
To default-initialize an object of type
T
means:
If
T
is a non-POD class type (clause 9), the default constructor forT
is called (and the initialization is ill-formed ifT
has no
accessible default constructor).If
T
is an array type, each element is default-initialized.Otherwise, the object is zero-initialized.
With this code
struct Int { int i; };
int main()
{
Int a;
}
the object a
is default-initialized, but clearly a.i
is not necessarily equal to 0 . Doesn't that contradict the standard, as Int
is POD and is not an array ?
Edit Changed from class
to struct
so that Int
is a POD.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从2003年标准的8.5.9开始:
您显示的类是 POD,因此突出显示的部分适用,并且您的对象根本不会被初始化(因此您引用的第 8.5/5 节根本不适用)。
编辑:根据您的评论,这里引用当前标准最终工作草案第 8.5/5 节(我没有真正的标准,但 FDIS 据说非常接近):
From 8.5.9 of the 2003 standard:
The class you show is a POD, so the highlighted part applies, and your object will not be initialized at all (so section 8.5/5, which you quote, does not apply at all).
Edit: As per your comment, here the quote from section 8.5/5 of the final working draft of the current standard (I don't have the real standard, but the FDIS is supposedly very close):
您的变量未初始化。
用于
初始化您的 POD 或声明标准构造函数以使其成为非 POD;
但出于性能原因,您也可以使用未初始化的 POD,例如:
Your variable is not initialized.
Use
to initialize your POD or declare a standard constructor to make it non POD;
But you can also use your POD uninitialized for performance reasons like:
不,对象
a
未默认初始化。如果你想默认初始化它,你必须说:No, the object
a
is not default-initialized. If you want to default-initialize it, you have to say: