“int a = int();”必然给我一个零? [英] Does "int a = int();" necessarily give me a zero?
问题描述
int a = int();
必须给我一个零吗?
如果 int
被替换为 char
double
, bool
或指针类型?
> int a = int(); 必须给我一个零吗?
该标准保证它给你零。
这被称为值初始化。对于 int
类型,价值初始化基本上是零初始化。
在语言标准中指定的位置在哪里?
< blockquote>
这些规则在第8.5节中的标准中有明确规定。
我将在这里将相关的内容引用到Q:
C ++ 03:8.5初始化程序
第7项:
初始化程序是一组空括号的对象, ),应进行值初始化。
价值初始化&零初始化在 8.5 Para 5 中定义为:
要 value-initialize 类型T的对象意味着:
- 如果T是带有用户声明的构造函数(12.1)的类类型(第9节),则默认
调用T的构造函数(如果T没有可访问的
默认构造函数,则初始化是不成形的);
- 如果T是一个没有用户声明的构造函数的非联合类类型,那么T的每个非静态
数据成员和基类组件都被初始化;
- 如果T是数组类型,则每个元素都被初始化;
- 否则,对象为零初始化
要将类型T的对象
初始化表示:
- 如果T是标量类型(3.9),则将对象设置为转换为T ;
- 如果T是非联合类类型,则每个非静态数据成员和每个基类子对象
都是零初始化的;
- if T是一个联合类型,对象的第一个命名数据成员是零初始化的;
- 如果T是一个数组类型,每个元素都是零初始化的;
- 如果T是参考类型,不执行初始化。
注意:粗体文字由我强调。
Does
int a = int();
necessarily give me a zero?How about if
int
is replaced bychar
,double
,bool
or pointer type?Where is this specified in the language standard, please?
解决方案Does
int a = int();
necessarily give me a zero?Yes, the standard guarantees that it gives you zero.
This is known as Value Initialization. For the typeint
, Value Initialization basically ends up being an Zero Initialization.Where is this specified in the language standard, please?
The rules are clearly specified in the standard in section 8.5. I will quote the relevant ones to the Q here:
C++03: 8.5 Initializers
Para 7:An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized.
Value Initialization & Zero Initialization are defined in 8.5 Para 5 as:
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-initializedTo 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.Note: The bold texts are emphasized by me.
这篇关于“int a = int();”必然给我一个零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!