Question

Suppose structs A and B are singleton structs defined as follows:

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()) { ... }
};

Suppose that the file structure is organized so that the code will compile.

The first time A::shared_a is called, it will construct the shared instance of A. The constructor for the shared instance of A will call B::shared_b, which will construct the shared instance of B. Next, the constructor for the shared instance of B will call A::shared_a. However, the shared instance of A has not finished its constructor! Therefore, these constructors will loop infinitely.

In order to prevent such a loop, I could merge classes A and B, but I would like to avoid doing so. Is there a more elegant solution?

Thanks,

Sam

Was it helpful?

Solution

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.

OTHER TIPS

How about you give the shared_a() a reference of B itself so in the A_constructor of shared_a it can set that reference to be its b_?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top