0

假设结构 A 和 B 是定义如下的单例结构:

struct A
{
    B& b_;
    static A& shared_a() { ... }
    A() : b_(B::shared_b()) { ... }
};

struct B
{
    A& a_;
    static B& shared_b() { ... }
    B() : a_(A::shared_a()) { ... }
};

假设文件结构被组织,以便代码可以编译。

第一次调用A::shared_a,会构造A的共享实例。A的共享实例的构造函数会调用B::shared_b,B::shared_b会构造B的共享实例。接下来,共享的构造函数B 的实例将调用 A::shared_a。但是,A 的共享实例还没有完成它的构造函数!因此,这些构造函数将无限循环。

为了防止这样的循环,我可以合并类 A 和 B,但我想避免这样做。有没有更优雅的解决方案?

谢谢,

山姆

4

2 回答 2

1

Your code exhibits undefined behavior, and you might get either the infinite loop that you mention or any other weird behavior. Now, the problem is not with how to solve it, but rather break the cyclic dependency, which is usually a code smell.

If you are still convinced that your design makes sense, and if your constructors only store the references (without using the objects) you can change the constructors to take a reference to the object.

Again, I would avoid the cyclic dependency.

于 2012-05-07T02:55:15.020 回答
0

你如何给 shared_a() 一个 B 本身的引用,以便在 shared_a 的 A_constructor 中它可以将该引用设置为它的 b_?

于 2012-05-07T02:15:09.797 回答