0

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?
Dave
  • 7,555
  • 8
  • 46
  • 88
  • Why do you think that `singletonFoo` is not thread safe? – ecatmur Feb 24 '15 at 16:27
  • @ecatmur, [It wasn't prior to C++11.](http://stackoverflow.com/questions/8102125/is-local-static-variable-initialization-thread-safe-in-c11) – chris Feb 24 '15 at 16:28
  • @ecatmur Because C++98 doesn't guarantee static local initialization to be thread safe (since it doesn't mention threads at all). – Mark B Feb 24 '15 at 16:29
  • www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf – Dave Feb 24 '15 at 16:30

1 Answers1

2
  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.
Mark B
  • 95,107
  • 10
  • 109
  • 188
  • non-static means "not declared with static", i.e. automatic storage duration variables. – Dave Feb 24 '15 at 16:37