博文

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

摘要:实际应用中我们在定义一个数组的时候常常希望他能按照我们的想像初始化,比如: 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 compon......

阅读全文(5439) | 评论:0