// edited by Neil Butterworth to conserve vertical space
#include <stdio.h>
struct A;
struct B;
A& GetAInstance();
B& GetBInstance();
struct A {
A() {
printf( "A\n" );
}
~A() {
printf( "~A\n" );
B& b = GetBInstance();
}
};
struct B {
B() {
printf( "B\n" );
}
~B() {
printf( "~B\n" );
A& a = GetAInstance();
}
};
A& GetAInstance() {
static A a;
return a;
}
B& GetBInstance() {
static B b;
return b;
}
int main( ) {
A a;
}
Consider the above scenario. I would expect this to result in an infinite reference loop resulting in the program being unable to exit from static de-initialization, but the program ran just fine with the following printout:
A
~A
B
~B
A
~A
Which was unexpected.
How does a compiler deal with this situation? What algorithms does it use to resolve the infinite recursion? Or have I misunderstood something fundamental? Is this, somewhere in the standard, defined as undefined?