c – 文件中模板类的静态数据成员的初始化顺序是什么?

前端之家收集整理的这篇文章主要介绍了c – 文件中模板类的静态数据成员的初始化顺序是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在给定的文件中,如果我有,
struct A { static int a; };
struct B { static int b; };
int A::a;
int B::b;

然后,我总是可以期望A :: a在B :: b之前被初始化.现在对于同一个文件,采取模板案例,

template<typename T>
struct X { static T t; };
template<typename T>
T X<T>::t;

假设,X用A和B实例化,并且其静态成员在代码中的某处任意使用,如X< A> :: t和X< B> :: t,则应该是模板静态成员初始化的顺序X< T> ::吨; ?它定义明确吗?

解决方法

只要模板只有一个定义(例如,您只有一个翻译单元),它就是定义明确的.静态成员按照在需要定义静态数据成员的上下文中实例化模板特化的顺序进行初始化.来自C 03标准的§14.7.1/ 1 [temp.inst](强调我的):

Unless a class template specialization has been explicitly instantiated (14.7.2) or explicitly specialized (14.7.3),the class template specialization is implicitly instantiated when the specialization is referenced in a context that requires a completely-defined object type or when the completeness of the class type affects the semantics of the program. The implicit instantiation of a class template specialization causes the implicit instantiation of the declarations,but not of the definitions or default arguments,of the class member functions,member classes,static data members and member templates; and it causes the implicit instantiation of the definitions of member anonymous unions. Unless a member of a class template or a member template has been explicitly instantiated or explicitly specialized,the specialization of the member is implicitly instantiated when the specialization is referenced in a context that requires the member definition to exist; in particular,the initialization (and any associated side-effects) of a static data member does not occur unless the static data member is itself used in a way that requires the definition of the static data member to exist.

§14.7.1/ 7还规定:

The implicit instantiation of a class template does not cause any static data members of that class to be implicitly instantiated.

但是,当您有多个定义模板的翻译单元时,事情变得更加复杂. §3.2/ 5 [basic.def.odr]指出:

There can be more than one definition of a class type (clause 9),enumeration type (7.2),inline function with external linkage (7.1.2),class template (clause 14),non-static function template (14.5.5),static data member of a class template (14.5.1.3),member function of a class template (14.5.1.1),or template specialization for which some template parameters are not specified (14.7,14.5.4) in a program provided that each definition appears in a different translation unit,and provided the definitions satisfy the following requirements. Given such an entity named D defined in more than one translation unit,then

(list of conditions…)

If the definitions of D satisfy all these requirements,then the program shall behave as if there were a single definition of D. If the definitions of D do not satisfy these requirements,then the behavior is undefined.

请注意,标准没有指定将哪个定义作为单个定义,只是选择了某个定义.因此,如果多个翻译单元以不同的顺序实例化模板,则无法保证初始化的顺序.

猜你在找的C&C++相关文章