隐式与显式默认构造函数调用

Implicit vs. Explicit Default Constructor Call

假设我对以下两种创建调用默认构造函数(由编译器提供)的对象的方法的了解都是正确的。

class A
{
    int a,b;
    //No programmer defined constructor
}
...
A o1; //Implicit Call I believe
A o2 = A(); //Explicit Call

为什么 A o2 = A(); 导致对象 o2 的成员 (a,b) 使用默认值 (0) 而不是 A o; 初始化自身(它们使用垃圾值初始化)?它是未定义的行为吗?

引用自标准 p8.5/1

这里没有用户定义的构造函数,因此,编译器将使用默认构造函数。并且默认构造函数不会用零初始化成员。

If no initializer is specified for an object, the object is default-initialized.

To default-initialize an object of type T means:

If T is a (possibly cv-qualified) class type (Clause 9), constructors are considered. The applicable constructors are enumerated (13.3.1.3), and the best one for the initializer () is chosen through overload resolution (13.3). The constructor thus selected is called, with an empty argument list, to initialize the object.

第二种情况是值初始化。

An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized.

To value-initialize an object of type T means:

if T is a (possibly cv-qualified) class type without a user-provided or deleted default constructor, then the object is zero-initialized and the semantic constraints for default-initialization are checked, and if T has a non-trivial default constructor, the object is default-initialized;

To zero-initialize an object or reference of type T means:

if T is a (possibly cv-qualified) non-union class type, each non-static data member and each base-class subobject is zero-initialized and padding is initialized to zero bits;

在这两种情况下,都会调用编译器提供的默认构造函数。很可能 C++ 编译器将值初始化为一些垃圾值。在调用默认构造函数的情况下,C++ 编译器不会将值初始化为 0,除非内存已被转储为零。我试过这种情况,我没有看到在两个对象中为 a 和 b 分配的值有任何差异。