构造函数初始化列表中的循环依赖

Circular dependency in constructor initialization list

下面的定义是否明确?

class A;
class B;

// define A, which takes B& in constructor
// define B, which takes A& in constructor

class C
{
    A a;
    B b;
public:
    C() : a(b), b(a) { /* stuff with a and b */ }
}

完整示例位于 ideone.com

是否 safe/well-defined 只要 AB 的构造函数不对他们获得的引用做任何事情?

N4140 [class.cdtor]/1 读取:

For an object with a non-trivial constructor, referring to any non-static member or base class of the object before the constructor begins execution results in undefined behavior. For an object with a non-trivial destructor, referring to any non-static member or base class of the object after the destructor finishes execution results in undefined behavior.

虽然这段话本身并不意味着行为在其他方面是明确定义的,但以下示例表明它是。以下是摘录:

struct B : public A { int j; Y y; }; // non-trivial
extern B bobj;
B* pb = &bobj; // OK

所以答案是:是的,如果您没有在 A 的构造函数中引用 b 的成员或基数 类,则您的行为定义明确.