问题1:
struct S { size_t size; int j; int k; int l; }; S s={sizeof(S)};
C++标准有没有说,上面这种{}的初始化方式,会把j,k,l都赋成0值?
标准文档里面有说道吗?
问题2:
int main() { int* pi=new int[5]; for(int i=0;i<5;++i) cout<<pi[i]<<","; return 0; }
这里pi的5个值都是没有初始化的,本人运行的结果可能是:
6785200,6782912,0,0,0,
而假如本人改成
int main() { int* pi=new int[5]();//use () for(int i=0;i<5;++i) cout<<pi[i]<<","; return 0; }
这样,那么pi的5个元素打印出来就一定是0.
C++标准有没有规定指针数组也可以用()来赋值,()内不指定就是0?
很奇怪的是,假如本人在括号里面指定一个初始值,例如7:
int* pi=new int[5](7);
那么这句话就编译不过了,为什么不行呢?
本人希望把pi里面的元素都赋值为7,能否在初始化的时候就做到?
解决方案
80
/*That"s not quite true (you should almost certainly get yourself an alternative reference), you are allowed an empty initializer (()) which will value-initialize the array but yes, you can"t initialize array elements individually when using array new. (See ISO/IEC 14882:2003 5.3.4 [expr.new] / 15) E.g. */ int* p = new int[5](); // array initialized to all zero int* q = new int[5]; // array elements all have indeterminate value /*There"s no fundamental reason not to allow a more complicated initializer it"s just that C++03 didn"t have a grammar construct for it. In the next version of C++ you will be able to do something like this. */ int* p = new int[5] {0, 1, 2, 3, 4};
10
value-initialization