#include <iostream>
struct D{};
struct B{};
struct C
{
C();
};
struct A
{
A();
B * b;
C * c;
D * d;
static A& pInstance()
{
static A a;
return a;
}
};
A::A()
{
b = new B;
c = new C;
d = new D;
}
C::C()
{
A::pInstance().b;
}
int main()
{
A::pInstance();
std::cin.ignore();
}
Is there potentially any problems with the above case, as the C constructor call A field while A class not yet construted entirely.
I have this code in production. The application seems to crash randomly at starting, I am wondering if this can be due to this “poor” design.
It’s explicitly stated as Undefined Behavior: (§ 6.7/4) “If control re-enters the declaration recursively while the variable is being initialized, the behavior is undefined.”