I am trying the following C++ code, which initializes member variables c1
and c2
based on the static variables v1
and v2
in different namespaces. It seems to me that cyclic dependency occurs for initialization of those variables.
#include <iostream>
namespace M1
{
struct T1
{
int c1;
T1();
};
T1 v1;
}
namespace M2
{
struct T2
{
int c2;
T2() { c2 = M1::v1.c1; } // (1)
// T2() : c2( M1::v1.c1 ) {} // (2)
};
T2 v2;
}
M1::T1::T1() { c1 = M2::v2.c2; } // (3)
// M1::T1::T1() : c1( M2::v2.c2 ) {} // (4)
int main()
{
std::cout << M1::v1.c1 << std::endl;
std::cout << M2::v2.c2 << std::endl;
return 0;
}
However, if I compile this code with g++-5.3 (installed via homebrew on OSX 10.9), it always complies successfully (with no warning with -Wall
) and gives
0
0
I also tried replacing lines (1) and (3) by (2) and (4), but no change in the results (i.e., 0
and 0
). So I am wondering why this code works successfully. No cyclic dependency here? If not, is the result simply undefined? (i.e., garbage data in the memory for c1 and c2 printed?) I would appreciate any hints on this behavior. Thanks!