什么使静态变量只初始化一次? [英] What makes a static variable initialize only once?

查看:280
本文介绍了什么使静态变量只初始化一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,如果你在代码中初始化一个静态变量C ++,初始化只运行第一次运行该函数。

I noticed that if you initialize a static variable in C++ in code, the initialization only runs the first time you run the function.

这很酷,是实现?它是否翻译成某种扭曲的if语句? (如果给定值,则..)

That is cool, but how is that implemented? Does it translate to some kind of twisted if statement? (if given a value, then ..)

void go( int x )
{
    static int j = x ;
    cout << ++j << endl ; // see 6, 7, 8
} 

int main()
{
    go( 5 ) ;
    go( 5 ) ;
    go( 5 ) ; 
}


推荐答案

转换为带有内部布尔标志的隐式 if 语句。所以,在最基本的实现中,你的声明通常翻译成

Yes, it does normally translate into an implicit if statement with an internal boolean flag. So, in the most basic implementation your declaration normally translates into something like

void go( int x ) {
  static int j;
  static bool j_initialized;

  if (!j_initialized) {
    j = x;
    j_initialized = true;
  }

  ...
} 

最重要的是,如果你的静态对象有一个非平凡的析构函数,语言必须服从另一个规则:这样的静态对象必须以与其构造相反的顺序被破坏。由于构建顺序只在运行时才知道,所以销毁顺序也在运行时定义。所以,每次你构造一个具有非平凡析构函数的本地静态对象,程序必须将它注册在某种线性容器中,它将在以后使用以正确的顺序破坏这些对象。

On top of that, if your static object has a non-trivial destructor, the language has to obey another rule: such static objects have to be destructed in the reverse order of their construction. Since the construction order is only known at run-time, the destruction order becomes defined at run-time as well. So, every time you construct a local static object with non-trivial destructor, the program has to register it in some kind of linear container, which it will later use to destruct these objects in proper order.

不用说,实际细节取决于实现。

Needless to say, the actual details depend on implementation.

它涉及到用编译时常量初始化的原始类型的静态对象(例如在你的例子中 int ),编译器可以在启动时自由初始化该对象。你永远不会注意到差别。但是,如果你使用一个更复杂的例子与一个非原始对象

It is worth adding that when it comes to static objects of "primitive" types (like int in your example) initialized with compile-time constants, the compiler is free to initialize that object at startup. You will never notice the difference. However, if you take a more complicated example with a "non-primitive" object

void go( int x ) {
  static std::string s = "Hello World!";
  ...

code>是你应该期望在生成的代码中找到,即使对象使用编译时常数初始化。

then the above approach with if is what you should expect to find in the generated code even when the object is initialized with a compile-time constant.

在你的情况下,初始化器是在编译时不知道,这意味着编译器必须延迟初始化并使用隐式 if

In your case the initializer is not known at compile time, which means that the compiler has to delay the initialization and use that implicit if.

这篇关于什么使静态变量只初始化一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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