问题描述
为什么这两种情况(A和C的初始化)在C ++ 14中产生不同的默认初始化结果?
基于cppreference.com中的默认初始化规则,我无法理解结果
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;
}
输出:
(Scenario 1)
0
-1771317376
-1771317376
0
--------------------
(Scenario 2)
0
0
0
0
试图解释这一点的帖子(但是我还不清楚为什么结果的差异以及在每种情况下导致m初始化的原因):
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
推荐答案
A
没有用户定义的构造函数,因此生成了默认构造函数。 C
具有用户定义的构造函数,因此不能保证会生成默认的构造函数,尤其是由于用户定义的构造函数会重载默认的构造函数。几乎可以肯定,C的每个构造都使用用户定义的构造函数。
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.
在用户定义的 C
构造函数中使用初始化列表对 C :: m
进行值初始化。初始化 C :: m
时,将对其进行值初始化,其中包括零初始化。
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;
和 A b;
是默认初始化。这不会设置为其成员分配任何值。 A :: m
中存储的值是未定义的行为。
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( );
和 A c {};
是值初始化。作为值初始化的一部分,它将执行零初始化。
new A();
and A c{};
are value initializations. As part of the value initialization, it performs a zero initialization.
这篇关于C ++默认初始化类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!