#include <iostream> #include <vector> class A { public: int i; A() {} }; A a1; A aa1[3]; std::vector<A> av1(3); int main() { A a2; A aa2[3]; std::vector<A> av2(3); std::cout << a1.i << " " << a2.i << std::endl; // 0 undefined std::cout << aa1[0].i << " " << aa2[0].i << std::endl; // 0 undefined std::cout << av1[0].i << " " << av2[0].i << std::endl; // undefined undefined }
在上面的代码中,只有a1.i和aa1 [0~2] .i被初始化为0,而其他的是未初始化的.我不知道为什么会这样.
具体来说,我所知道的是(来自“C Primer”):
>初始化过程是:
> a1和a2默认初始化.
> aa1和aa2的每个元素都是默认初始化的.
> av1和av2的每个元素都是初始值.
>默认初始化的过程是:
>检查变量是内置类型还是类类型.
>对于内置类型,如果变量在任何函数体之外,则将其初始化为0,否则该值未定义.
>对于类类型,如果类具有默认ctor,则调用它,否则它是编译错误.
>初始化值的过程是:
>检查变量是内置类型还是类类型.
>对于内置类型,它被初始化为0.
>对于类类型,它是默认初始化的. (我认为这意味着如果类具有默认ctor,否则它是编译错误.)
这样当调用ctor A :: A()时,数据成员A :: i如何初始化(我猜它是默认初始化的)?为什么只有a1.i和aa1 [0~2] .i被初始化为0,而其他的是未初始化的?
解决方法
when the ctor A::A() is called,how the data member A::i initialized
如果未提供初始化程序,则应用默认初始化规则.你的构造函数没有初始化A :: i所以它没有初始化;它的价值是不确定的.毫无疑问.摘自documentation on default initialization:
If T is a class type,the constructors are considered and subjected to overload resolution against the empty argument list. The constructor selected (which is one of the default constructors) is called to provide the initial value for the new object.
why only a1.i and aa1[0~2].i are initialized to 0,while others are uninitialized?
全局数据存储器初始化为零,即整个部分被清零,因此您看到全局A ::被初始化为0.请注意,构造函数不会这样做.摘自documentation:
Static initialization
[…]
2) For all other non-local static and thread-local variables,07002 takes place. In practice,variables that are going to be zero-initialized are placed in the .bss segment of the program image,which occupies no space on disk,and is zeroed out by the OS when loading the program.
但是,对于向量,向量本身位于非本地静态内存中,而其元素在自由存储(堆)中分配,因此它们的成员也是未初始化的.