Can the compiler deal with the initialization order of static variables correctly?

删除回忆录丶 提交于 2019-12-10 18:17:19

问题


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

a.h

template<class T>
struct A { static double a; };

template<class T>
double A<T>::a = 1;

b.h

struct B { static double b; };

b.cpp

#include "b.h"
#include "a.h"

double B::b = A<int>::a;

回答1:


In your example, A<int>::a is initialized statically, and all static initialization takes place before any dynamic initialization. B::b is initialized dynamically and so it will happen after A<int>::a is initialized, and everything is fine.




回答2:


In this case, there is no issue since a is initialised statically; this is guaranteed to happen before the dynamic initialisation of b.

More generally, where both require dynamic initialisation, this is an issue. Unless you specialise the template member before using it to initialise b, there is no guaranteed order. To quote the standard (C++11 3.6.2/2):

Definitions of explicitly specialized class template static data members have ordered initialization. Other class template static data members (i.e., implicitly or explicitly instantiated specializations) have unordered initialization.



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

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