“值初始化”是什么意思?有什么意思吗?
例如,如果我有一个类:
class Info
{
int x;
int y;
};
我用它来创建一个对象,
Info *p = new Info();
Info 旁边的括号是否意味着我正在对其进行值初始化?它与 Info *p = new Info;
有什么不同?
我知道有一个 问题区分新旧C++语言中的不同含义,但我想知道默认值初始化和值初始化之间的语义差异,例如值初始化是否意味着将某些内容初始化为零?
Possible Duplicate:
What do the following phrases mean in C++: zero-, default- and value-initialization?
If I have a class for example:
class Info
{
int x;
int y;
};
which I used to created an object,
Info *p = new Info();
Does the brackets beside Info mean i'm value initializing it? How does it different from this, Info *p = new Info;
?
I know there is a question which differentiate between different meanings in new and old C++ language but I want to know the semantic difference between default and value initialization e.g. Does value initialization means initializing something to zero?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
声明的变量可以是零初始化、值初始化或默认初始化。
在您的示例中:
C++03 标准 8.5/5 恰当地定义了每个:
对 T 类型的对象进行零初始化意味着:
- 如果 T 是标量类型 (3.9),则设置该对象将值 0(零)转换为 T;
— 如果 T 是非联合类类型,则每个非静态数据成员和每个基类子对象
是零初始化的;
— 如果 T 是联合类型,则对象的第一个命名数据成员为零初始化;
— 如果 T 是数组类型,则每个元素均初始化为零;
— 如果 T 是引用类型,则不执行初始化。
默认初始化 T 类型的对象意味着:
— 如果 T 是非 POD 类类型(第 9 条),则调用 T 的默认构造函数(并且
如果 T 没有可访问的默认构造函数,则初始化是错误的);
— 如果 T 是数组类型,则每个元素都默认初始化;
— 否则,该对象将被零初始化。
对类型 T 的对象进行值初始化意味着:
— 如果 T 是具有用户声明的构造函数 (12.1) 的类类型(第 9 条),则默认值
调用 T 的构造函数(如果 T 没有可访问的,则初始化是错误的
默认构造函数);
— 如果 T 是没有用户声明的构造函数的非联合类类型,则每个非静态
T 的数据成员和基类组件已进行值初始化;
— 如果 T 是数组类型,则每个元素都是值初始化的;
— 否则,该对象被零初始化
A declared variable can be Zero Initialized, Value Initialized or Default Initialized.
In your example:
The C++03 Standard 8.5/5 aptly defines each:
To zero-initialize an object of type T means:
— if T is a scalar type (3.9), the object is set to the value of 0 (zero) converted to T;
— if T is a non-union class type, each nonstatic data member and each base-class subobject
is zero-initialized;
— if T is a union type, the object’s first named data member is zero-initialized;
— if T is an array type, each element is zero-initialized;
— if T is a reference type, no initialization is performed.
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.
To value-initialize an object of type T means:
— if T is a class type (clause 9) with a user-declared constructor (12.1), then the default
constructor for T is called (and the initialization is ill-formed if T has no accessible
default constructor);
— if T is a non-union class type without a user-declared constructor, then every non-static
data member and base-class component of T is value-initialized;
— if T is an array type, then each element is value-initialized;
— otherwise, the object is zero-initialized