用C POD类型的缺省初始化++(Default initialization of POD typ

2019-07-20 23:27发布

我知道有些POD变量默认初始化,但有些则没有。 (POD类型包括intfloat ,指针,工会,POD类型的数组,POD类型的结构等)

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

具体而言,其中以下将被隐式初始化:

  • 具有自动存储局部变量
  • 静态局部变量
  • 静态全局变量
  • 外部变量
  • 变量与分配的new
  • 一类POD成员(没有明确初始化在构造函数中)

我知道有关于这方面的一些情况存在的问题,但没有一个全面的(它们只能解决特定的情况下)。

Answer 1:

Local variables with automatic storage duration are not being initialized automatically. Since using uninitialized variables produces undefined behavior, it is a good practice to explicitly initialize your variables even when it's redundant.

About POD types that are being zero-initialized, C++03 standard 3.6.2 Initialization of non-local objects states:

§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.

So it's guaranteed by standard that POD types with static storage duration (whatever their scope is) will be zero-initialized.

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

This situation is described in 12.6.2 Initializing bases and members, that states (selected parts):

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.

Example:

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 !!!
}


Answer 2:

如果我们只谈论荚那么只有局部和全局静态外部变量 ,因为它们必须在某个地方定义。

与分配POD中new也被初始化有时 -如果你做初始化明确:

int* x = new int();

将创建一个int初始化为0x指向它,而

int* x = new int;

x点未初始化int

有时- POD类成员 -他们可以明确初始化(没有在构造函数中存在):

struct X
{
   int x;
};

X x;        //x.x is not initialized
X y = X();  //y.x is 0


文章来源: Default initialization of POD types in C++