简体   繁体   English

静态变量生存期,文件作用域与功能范围

[英]Static variable lifetimes, file-scope vs. function scope

suppose I have a .cpp file: 假设我有一个.cpp文件:

static Foo aFoo;

Foo& staticFoo(){
    return aFoo; 
}

Foo& singletonFoo(){ // not thread safe in c++-03
    static Foo staticFoo;
    return staticFoo;
}

and a .h file that exposes these functions (but not aFoo directly). .h文件公开这些功能(但不直接显示aFoo )。

  1. Am I certain that aFoo is initialized prior to staticFoo ? 我确定aFoo会在staticFoo之前初始化吗?
  2. Am I certain that staticFoo is destroyed after aFoo ? 我确定staticFoo之后aFoo被销毁了吗?
  3. Am I certain that aFoo is destroyed after any automatic storage duration variables in my program? 我确定程序中的任何自动存储持续时间变量之后aFoo被销毁了吗?
  1. No. If someone calls singletonFoo from another translation unit during static initialization then it's unspecified. 否。如果有人在静态初始化期间从另一个翻译单元调用singletonFoo ,则未指定。
  2. No because the destruction happens in reverse order of construction and we already established that construction is not guaranteed. 否,因为破坏是按照相反的顺序进行的,因此我们已经确定不能保证施工。
  3. aFoo will be destroyed after all local/automatic variables. 所有本地/自动变量之后, aFoo将被销毁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM