构造函数初始化列表中的循环依赖 [英] Circular dependency in constructor initialization list

查看:172
本文介绍了构造函数初始化列表中的循环依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是否定义良好?

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 上的完整示例。

它的安全/定义良好,只要 A B 不要对他们得到的引用做任何事情?

Is it safe/well-defined so long as the constructors for A and B don't do anything with the references they get?

推荐答案

N4140 [class.cdtor] / 1显示:

N4140 [class.cdtor]/1 reads:


对于具有非平凡构造函数的对象,在构造函数开始执行之前引用对象
的任何非静态成员或基类将导致未定义的行为。对于具有非平凡
析构函数的对象,在析构函数完成
之后引用对象的任何非静态成员或基类,会导致未定义的行为。

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.

虽然这段代码本身并不意味着行为是其他定义良好的,下面的例子显示它是。这里是一段摘录:

While this passage itself doesn't imply that the behavior is otherwise well-defined, the following example shows that it is. Here is an excerpt:

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

所以答案是:是的,你的情况下的行为是很好的定义,如果你在 A 的构造函数中引用 b 的成员或基类。

So the answer is: yes, the behavior in your case is well defined if you aren't referring to members or base classes of b in the constructor of A.

这篇关于构造函数初始化列表中的循环依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆