问题
Why those two scenarios (the initialization of A and of C ) produce different default initialization results in C++ 14? I can't understand the result based on the default initialization rules in 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<<b.m<<endl;
cout<<c.m<<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
The post that tries to explain this (but it's not clear to me yet why the difference in the results and what causes m to be initialized in each scenario): Default, value and zero initialization mess
回答1:
A has no user defined constructors, so a default constructor was generated. C has a user defined constructor, so there is no guarantee that a default constructor was generated, especially since the user defined constructor overloads the default constructor. It is almost certain that every construction of C used the user defined constructor.
In the user defined constructor for C uses an initialization list to value initialize C::m. When C::m is initialized, it is value initialized, which includes a zero initialization.
new A; and A b; are default initializations. This does not set assign any values to their members. What value is stored in A::m is undefined behavior.
new A(); and A c{}; are value initializations. As part of the value initialization, it performs a zero initialization.
来源:https://stackoverflow.com/questions/45290121/c-default-initialization-types