实际应用中我们在定义一个数组的时候常常希望他能按照我们的想像初始化,比如: 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,同样这也是很”标准的“。

评论