在构造函数初始化列表中使用成员

Use member in constructor initializer list

我可以安全地使用成员来初始化其他成员吗?

class Class {
 public:
  Class(X argument) : memberA(argument), memberB(memberA) {}

  A memberA;
  B memberB;
};

这里我们使用构造函数的参数来初始化memberA。然后我们依赖于这发生在 memberB 初始化之前的事实,并使用 memberA.

初始化 memberB

如果我们假设 XABstd::string,则上述示例有效(使用 gcc 测试),只要我们不会更改成员的声明顺序。但这实际上是由标准保证的还是我滥用了编译器的实现细节?

是的,根据 class.base.init#15

这是安全的

The expression-list or braced-init-list of a mem-initializer is in the function parameter scope of the constructor and can use this to refer to the object being initialized.

这篇笔记还有一个 this->i 的例子来说明之前初始化的 class 成员可以用来初始化 mem-initializer 中的其他 class 成员。 (在这个例子中 this-> 只是为了消除成员和构造函数参数的歧义,两者都命名为 i)。

注意成员在使用之前已经初始化,因为从 class.base.init#13.3

... 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).