When are C ++ implicit types initialized to 0?

I had some doubts after discussing this issue with my colleagues ...

As the name is asked, when can we assume that the built-in types will be initialized to 0 instead of an unknown value?

Are there rules that differ between C ++ standards?

+5
source share
4 answers

Full rules are in [dcl.init] (C ++ 11). To summarize: if the initializer is not specified in the declaration, the object has the so-called initialization by default. For class types, this means that the default constructor is called. For types other than class, this means that initialization is not performed.

, [dcl.init] §9 : " , ".

, ( ) non-class . (, ) not.

+6

:

++ 98 ++ 03:

3.6.2 , §1:

(3.7.1) (8.5), .

3.7.1 , §1:

, , .

3.7.1 , §3:

static .

8.5 , §6:

.

. ++ 98 8.5 §6:

, , .


:

, x y , , . , POD a b, , , , (i d) :

struct POD {
    int i;
    double d;
};

int x;
POD a;

int foo() {
    static int y;
    return y;
}

int main() {
    static POD b;
    std::cout << "x   = " << x      << std::endl;
    std::cout << "y   = " << foo()  << std::endl;
    std::cout << "a.i = " << a.i    << std::endl;
    std::cout << "b.d = " << b.d    << std::endl;
}

, , :

x   = 0
y   = 0
a.i = 0
b.d = 0
+3

, : POD 0, , :

struct POD {
   int    a;
   double b; //...
};
// namespace level:
POD p;
void f() {
   POD n1;                  // uninitialized
   POD p1 = {};
   POD p2 = POD();
   POD* n2 = new POD;       // uninitialized
   POD* pp1 = new POD();
   delete n2; delete pp1;
}

, "", . , , , . , VS T t = T(); T* p = new T()' (IIRC, T POD, , POD:/p >

struct T {
   std::string s;
   int         i;
};
void f() {
   T t = T();    // t.i == 0 according to the standard
}
+3

, - 0. , , /. _NO_DEBUG_HEAP = 1, , .

, , .

: , . - .

-1

All Articles