gpt4 book ai didi

c++ - POD 与非 POD 类类型的默认初始化

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:31:28 25 4
gpt4 key购买 nike

C++ 标准说 (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 for T is called (and the initialization is ill-formed if T has no accessible default constructor).

  • If T is an array type, each element is default-initialized.

  • Otherwise, the object is zero-initialized.

用这段代码

struct Int { int i; };

int main()
{
Int a;
}

对象 a 是默认初始化的,但显然 a.i 不一定等于 0 。这是否与标准相矛盾,因为 Int 是 POD 而不是数组?

编辑class 更改为 struct 以便 Int 是一个 POD。

最佳答案

来自 2003 年标准的 8.5.9:

If no initializer is specified for an object, and the object is of (possibly cv-qualified) non-POD class type (or array thereof), the object shall be default-initialized; if the object is of const-qualified type, the underlying class type shall have a user-declared default constructor. Otherwise, if no initializer is specified for a nonstatic object, the object and its subobjects, if any, have an indeterminate initial value); if the object or any of its subobjects are of const-qualified type, the program is ill-formed.

您显示的类是 POD,因此突出显示的部分适用,并且您的对象根本不会被初始化(因此您引用的第 8.5/5 节根本不适用)。

编辑: 根据您的评论,这里引用当前标准最终工作草案第 8.5/5 节的引述(我没有真正的标准,但 FDIS 据说非常关闭):

To default-initialize an object of type T means:

— if T is a (possibly cv-qualified) class type (Clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);

— if T is an array type, each element is default-initialized;

otherwise, no initialization is performed.

关于c++ - POD 与非 POD 类类型的默认初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8256293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com