成员初始化器列表中的初始化

Initialisation in Member Initializer List

class A
{
  public:
    int a ,b;
    A() : a(1)
    {
      b=3;
    }
};

如果我们创建这个 class 的对象:

A obj;

那么先初始化哪个,a还是b

在赋值的过程中b = 3会不会有默认构造函数的参与?我指的是提供的答案:If you use assignment then the fields will be first initialized with default constructors and then reassigned (via assignment operator) with actual values.

初始化顺序始终是声明变量的顺序,与内存初始化程序的顺序无关。所以 a 然后 b.

mem-initializer 首先按照它们在 class 定义中声明的顺序执行,然后执行构造函数的主体。

作为参考,C++ 标准草案说:

In a non-delegating constructor, initialization proceeds in the following order:

[...]

  • Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).

  • Finally, the compound-statement of the constructor body is executed

如果您没有在构造函数的主体中为 b 赋值,它将有一个 不确定的值

为了澄清 answer you mentioned,您似乎指的答案部分是:

if you use assignment then the fields will be first initialized with default constructors and then reassigned (via assignment operator) with actual values.

他们的意思是它将被默认初始化,在 int 的情况下意味着不确定的值,来自 C++ 标准草案:

If no initializer is specified for an object, the object is default-initialized. When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced (5.17).

注意 using an indeterminate value is undefined behavior.