正文

C++标准学习之数组的初始化2010-10-26 12:05:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/aurora/51936.html

分享到:

实际应用中我们在定义一个数组的时候常常希望他能按照我们的想像初始化,比如:

char buf1[10] = {0};

这样写的目的我想大部分都是期望编译器会为每个元素自动初始化为0。测试一下发现基本上所有编译器也都是这么做的,但这么做“标准”吗? 或者说可靠吗?

看看标准中是怎么说的吧:

8.5.1 Aggregates

7.  If there are fewer initializers in the list than there are members in the aggregate, then each   member not explicitly initialized shall be value-initialized (8.5).

[Example:
struct S { int a; char* b; int c; };
S ss = { 1, "asdf" };
initializes ss.a with 1, ss.b with "asdf", and ss.c with the value of an expression of the form
int(), that is, 0. ]

上面提到的 value-initialized 在8.5节给出了定义:

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
A program that calls for default-initialization or value-initialization of an entity of reference type is illformed.
If T is a cv-qualified type, the cv-unqualified version of T is used for these definitions of zeroinitialization,
default-initialization, and value-initialization.

可见char buf1[10] = {0};确实是符合标准的做法,它的确能够将每个元素都成功的初始化为0。

char buf1[10] = {1};这种做法确不能将每个元素初始化为1,同样这也是很”标准的“。

阅读(5533) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册