简体   繁体   中英

Static variable lifetimes, file-scope vs. function scope

suppose I have a .cpp file:

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).

  1. Am I certain that aFoo is initialized prior to staticFoo ?
  2. Am I certain that staticFoo is destroyed after aFoo ?
  3. Am I certain that aFoo is destroyed after any automatic storage duration variables in my program?
  1. No. If someone calls singletonFoo from another translation unit during static initialization then it's unspecified.
  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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