“值初始化”是什么意思? [英] What does 'value initializing' something mean?

查看:234
本文介绍了“值初始化”是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如果我有一个类,例如:

If I have a class for example:

class Info
{
   int x;
   int y;
};

我用来创建一个对象,

Info *p = new Info();

信息旁边的括号是否意味着值初始化?与此不同的是, 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?

推荐答案

声明的变量可以是零初始化 默认初始化

A declared variable can be Zero Initialized, Value Initialized or Default Initialized.

在您的示例中:

Info *p = new Info();    <------- Value Initialization
Info *p = new Info;      <------- Default Initialization

C ++ 03 Standard 8.5 / 5定义每个:

The C++03 Standard 8.5/5 aptly defines each:

初始化类型T的对象意味着:

To zero-initialize an object of type T means:

- 如果T是标量类型(3.9),则将对象设置为转换为T的值0(零);

- 如果T是非联合类类型,则每个非静态数据成员并且每个基类子对象

是零初始化的;

- 如果T是联合类型,则对象的第一个命名数据成员是零初始化的;

- 如果T是数组类型,则每个元素都进行零初始化;

- 如果T是引用类型,则不执行初始化。

— 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.

默认初始化类型T的对象意味着:

- 如果T是非POD类类型(第9节),调用T的默认构造函数(如果T没有可访问的默认构造函数,则
初始化不成功);

- 如果T是数组类型,每个元素是缺省初始化的;

- 否则,对象是零初始化的。

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.

值初始化类型T的对象意味着:

- 如果T是类类型)和用户声明的构造函数(12.1),则调用T的默认
构造函数(如果T没有可访问的
默认构造函数,则初始化不成功);

- 如果T是一个没有用户声明的构造函数的非union类型类型,那么T的每个非静态
数据成员和基类组件都被初始化;

- if T是一个数组类型,然后每个元素被初始化;

- 否则,对象是零初始化的

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

这篇关于“值初始化”是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆