编译器能否正确处理静态变量的初始化顺序? [英] Can the compiler deal with the initialization order of static variables correctly?

查看:35
本文介绍了编译器能否正确处理静态变量的初始化顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下情况如何?如果存在依赖,编译器能否正确处理静态变量的初始化顺序?

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;

推荐答案

在您的示例中,A<int>::a 是静态初始化的,并且所有静态初始化都发生在任何动态初始化之前.B::b 是动态初始化的,所以它会在 A::a 初始化后发生,一切正常.

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.

这篇关于编译器能否正确处理静态变量的初始化顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆