C++ 是什么让静态变量只初始化一次?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5567529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:25:50  来源:igfitidea点击:

What makes a static variable initialize only once?

c++variablesstaticstatic-variables

提问by bobobobo

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

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

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

这很酷,但它是如何实现的?它是否转化为某种扭曲的 if 语句?(如果给定一个值,那么..)

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

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

回答by AnT

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

是的,它通常会转换为if带有内部布尔标志的隐式语句。因此,在最基本的实现中,您的声明通常会转化为类似

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.

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



It is worth adding that when it comes to static objects of "primitive" types (like intin 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

值得补充的是,当涉及int使用编译时常量初始化的“原始”类型(如您的示例中)的静态对象时,编译器可以在启动时自由地初始化该对象。你永远不会注意到差异。但是,如果您使用“非原始”对象来举一个更复杂的示例

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

then the above approach with ifis 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.

在您的情况下,初始化程序在编译时未知,这意味着编译器必须延迟初始化并使用该隐式if.

回答by Jon

Yes, the compiler usually generates a hidden boolean "has this been initialized?" flag and an ifthat runs every time the function is executed.

是的,编译器通常会生成一个隐藏的布尔值“这是否已初始化?” 标志和if每次执行函数时运行的 。

There is more reading material here: How is static variable initialization implemented by the compiler?

这里有更多阅读材料:编译器如何实现静态变量初始化?

回答by Tony Delroy

While it is indeed "some kind of twisted if", the twist may be more than you imagined...

虽然它确实是“某种扭曲的如果”,但扭曲可能比你想象的要多……

ZoogieZork's comment on AndreyT's answer touches on an important aspect: the initialisationof static local variables - on some compilersincluding GCC - is by default thread safe(a compiler command-line option can disable it). Consequently, it's using some inter-thread synchronisation mechanism (a mutex or atomic operation of some kind) which can be relatively slow. If you wouldn't be comfortable - performance wise - with explicit use of such an operation in your function, then you should consider whether there's a lower-impact alternative to the lazy initialisation of the variable (i.e. explicitly construct it in a threadsafe way yourself somewhere just once). Very few functions are so performance sensitive that this matters though - don't let it spoil your day, or make your code more complicated, unless your programs too slow and your profiler's fingering that area.

ZoogieZork 对 AndreyT 的回答的评论涉及一个重要方面:静态局部变量的初始化- 在包括 GCC 在内的一些编译器上-默认情况下是线程安全的(编译器命令行选项可以禁用它)。因此,它使用了一些可能相对较慢的线程间同步机制(某种互斥或原子操作). 如果您对在函数中显式使用这样的操作感到不舒服 - 性能明智 - 那么您应该考虑是否有一个影响较小的替代变量的延迟初始化(即自己以线程安全的方式显式构造它)某处只是一次)。很少有函数对性能如此敏感以至于这很重要 - 不要让它破坏您的一天,或者使您的代码更复杂,除非您的程序太慢并且您的分析器正在使用该区域。

回答by Jeffrey Faust

They are initialized only once because that's what the C++ standard mandates. How this happens is entirely up to compiler vendors. In my experience, a local hidden flag is generated and used by the compiler.

它们只初始化一次,因为这是 C++ 标准要求的。这完全取决于编译器供应商。根据我的经验,本地隐藏标志是由编译器生成和使用的。