C中POD类型的默认初始化

我知道一些 POD变量是认初始化的,但其他变量不是. (POD类型包括int,float,指针,工会,POD类型的数组,POD类型的结构等)

范围和存储类如何影响POD类型的认初始化?

具体来说,以下哪一个将被隐式地初始化:

>具有自动存储的局部变量
>静态局部变量
>静态全局变量
>外部变量
>用新的分配的变量
>一个类的POD成员(在构造函数中没有显式初始化)

我知道现在有一些与这些情况有关的问题,但并不全面(仅针对具体情况).

解决方法

具有自动存储持续时间的本地变量尚未自动初始化.由于使用未初始化的变量会产生未定义的行为,因此即使在多余的情况下也能明确地初始化变量是一个好习惯.

关于正在初始化的POD类型,C 03标准3.6.2非本地对象的初始化状态:

§1 Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place. zero-initialization and initialization with a constant expression are collectively called static initialization; all other initialization is dynamic initialization. Objects of POD types (3.9) with static storage duration initialized with constant expressions (5.19) shall be initialized before any dynamic initialization takes place.

因此,通过标准保证具有静态存储持续时间(无论其范围)的POD类型将被零初始化.

POD members of a class (without explicit initialization in a constructor)

这种情况在12.6.2中描述,初始化基础和成员,其中指出(选定的部分):

If a given nonstatic data member or base class is not named by a mem-initializer-id (including the case where there is no mem-initializer-list because the constructor has no ctor-initializer),then:

— If the entity is a nonstatic data member…,and the entity class is a non-POD class,the entity is default-initialized (8.5)…

Otherwise,the entity is not initialized

After the call to a constructor for class X has completed,if a member of X is neither specified in the constructor’s mem-initializers,nor default-initialized,nor value-initialized,nor given a value during execution of the body of the constructor,the member has indeterminate value.

例:

class C
{
public:
    C(int x,int z) : x(x),z(z) { }
    int x,y,z;
};

int main(void)
{
    C* c = new C(1,3);
    std::cout << c->y; // value of y is undetermined !!!
}

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...