Can the compiler deal with the initialization order of static variables correctly if there is dependency?

浪子不回头ぞ 提交于 2019-12-12 14:06:54

问题


Can the compiler deal with the initialization order of static variables correctly if there is dependency? For example, I have

a.h:

struct A { static double a; };

a.cpp:

#include "a.h"
double A::a = 1;

b.h:

struct B { static double b; };

b.cpp:

#include "b.h"
#include "a.h"
double B::b = A::a;

回答1:


Within translation units the order of such initialization is specified. Across translation units the order is not specified.

So in your case, since statics will get zero initialized by default, B::b will definitely be 0 or 1.




回答2:


Nope. Static initialization order is undefined by the C++ standard. You can HOPE that your compiler is smart, but there's no guarantee.

Think about what would happen if you also have a "c" variable which is assigned with "b", and the "a" variable is assigned with "c". Then you've have a circular dependency, and it would compile, but you would end up with garbage values.



来源:https://stackoverflow.com/questions/18834548/can-the-compiler-deal-with-the-initialization-order-of-static-variables-correctl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!