Default initialization doesn't work properly

时间:2018-07-24 10:00:51

标签: c++ initialization default

class Example{

public:
int k;
};

int main(){
Example *ex = new Example();
Example *ex1 = new Example;
}

From what I have read so far, in the case of ex variable k will be value initialized, that means equals 0, and ex1 will be default initialized, and for basic types as int that means undefined behavior, but not 0. The problem is, when I print them

cout << ex->k << endl;
cout <<  ex1->k << endl;

it prints 0 for both. Why?

EDIT: According to C++ Standard - To zero-initialize an object of type T means:

— if T is a scalar type (3.9), the object is set to the value of 0 (zero) converted to T;
— if T is a non-union class type, each nonstatic data member and each base-class subobject is zero-initialized;
— if T is a union type, the object’s first named data member is zero-initialized;
— if T is an array type, each element is zero-initialized;
— if T is a reference type, no initialization is performed.

To default-initialize an object of type T means:
— if T is a non-POD class type (clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
— if T is an array type, each element is default-initialized;
— otherwise, the object is zero-initialized.

To value-initialize an object of type T means:
— if T is a class type (clause 9) with a user-declared constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
— if T is a non-union class type without a user-declared constructor, then every non-static data member and base-class component of T is value-initialized;
— if T is an array type, then each element is value-initialized;
— otherwise, the object is zero-initialized

The things look a little bit different to me now, in the case of ex1 we have default initialization, it's a POD class and not an array so , the object is zero-initialized, then - if T is a non-union class type, each nonstatic data member and each base-class subobject is zero-initialized; and that means that k will be initialized to 0 and it is not undefined behavior. Right ?

1 个答案:

答案 0 :(得分:1)

"Undefined behavior" means the compiler can do anything .Which is to say, that when you hit undefined behavior, the compiler would be completely within its rights to make demons fly out of your nose nasal demons.Thankfully,in your case it chose to print 0.