C ++ Default Initialization Types

Why do these two scenarios (initialization A and C) create different default initialization results in C ++ 14? I cannot understand the result based on the default initialization rules at cppreference.com

struct A { int m; }; struct C { C() : m(){}; int m; }; int main() { A *a, *d; A b; A c{}; a=new A(); d=new A; cout<<a->m<<endl; cout<<d->m<<endl; cout<<bm<<endl; cout<<cm<<endl; cout<<"--------------------"<<endl; C *a1, *d1; C b1; C c1{}; a1=new C(); d1=new C; cout<<a1->m<<endl; cout<<d1->m<<endl; cout<<b1.m<<endl; cout<<c1.m<<endl; } 

Output:

 (Scenario 1) 0 -1771317376 -1771317376 0 -------------------- (Scenario 2) 0 0 0 0 

A message that tries to explain this (but I still donโ€™t understand why the difference in results and the reasons why m will be initialized in each scenario): Default value, value and zero initialization mess

+4
c ++ initialization default-value c ++ 14
Jul 24 '17 at 21:10
source share
1 answer

A does not have user-defined constructors, so a default constructor was created. C has a user-defined constructor, so there is no guarantee that a default constructor has been generated, especially since a user-defined constructor overloads the default constructor. Almost certainly, every C construct uses a user-defined constructor.

The user-defined constructor for C uses an initialization list for the initialize value of C::m . When C::m is initialized, it is initialized with a value that enables zero initialization.

new A; and A b; are initializations by default. This does not set the assignment of any values โ€‹โ€‹to its members. What value is stored in A::m is undefined behavior.

new A(); and A c{}; - initialization of values. As part of initializing a value, it performs zero initialization.

-one
Jul 24 '17 at 22:33
source share



All Articles