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