它们在隐式构造函数、无参数空体构造函数和显式默认构造函数之间是否等效?

Are they equivalent between implicit ctor, no-parameter-empty-body ctor and explicit default ctor?

struct A1
{
    int n;        
};

struct A2
{
    int n;
    A2(){}        
};

struct A3
{
    int n;
    A3() = default;        
};

问题一:

C++标准是否保证类、A1A2A3完全等价?

问题二:

A1 a1;
A2 a2;
A3 a3;

编译器不会按照 C++ 标准对 a1.na2.na3.n 进行零初始化吗?

A1A3aggregate type 的区别之一,而 A2 不是,因为它有一个用户定义的构造函数。

class type (typically, struct or union), that has

  • ...
  • no user-provided, inherited, or explicit (since C++17) constructors (explicitly defaulted or deleted constructors are allowed) (since C++11)
  • ...

这意味着 A1A3 它们可以聚合初始化,而 A2 不能。

A1 a1{99}; // fine;  n is initialized to 99
A3 a3{99}; // fine;  n is initialized to 99
A2 a2{99}; // error; no matching constructor taking int found

Will the compiler not zero-initialize a1.n, a2.n, a3.n as per the C++ standard?

根据default initialization, if they're of automatic storage duration, no zero-initialization here, all values will be indeterminate. On the other hand, static and thread-local objects get zero initialized.

的规则

它们不相等,因为它们是不同的实体并且具有不同的初始化:第一个和最后一个是聚合,第二个不是

An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no brace-or-equal-initializers for non-static data members (9.2), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).

在此处阅读更多相关信息:What are Aggregates and PODs and how/why are they special?

因此聚合初始化适用于 A1A3,但不适用于 A2

struct A1
{
    int n;        
};

struct A2
{
    int n;
    A2(){}        
};

struct A3
{
    int n;
    A3() = default;        
};


int main()
{
   A1 obj1{42};
   //A2 obj2{42}; // error
   A3 obj3{42};


   return 0;
}

A1 a1; A2 a2; A3 a3;

Will the compiler not zero-initialize a1.n, a2.n, a3.n as per the C++ standard

变量将是 default initialized