c++initializationlanguage-lawyerbuilt-in-types

In what cases are objects zero-initialized instead of default-initialized?


I grew some doubts after discussing this with colleagues...

As the title asks, when can it be assumed that built-in types will be initialized to 0 instead of an unknown value?

Do the rules vary among the c++ standards?


Solution

  • The full rules are in [dcl.init] (C++11). To summarize: when no initialiser is provided in a declaration, the entity is so-called default-initialised. For class types, this means the default constructor is called. For non-class types, this means no initialisation is performed.

    However, [dcl.init] §9 states: "Every object of static storage duration is zero-initialized at program startup before any other initialization takes place."

    This means that static-duration variables (such as namespace-scope variables) of non-class type are zero-initialised. Other objects of non-class types (such as local variables) are not initialised.