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?
4
  • Why do you think that singletonFoo is not thread safe? Commented Feb 24, 2015 at 16:27
  • @ecatmur, It wasn't prior to C++11. Commented Feb 24, 2015 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). Commented Feb 24, 2015 at 16:29
  • www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf Commented Feb 24, 2015 at 16:30

1 Answer 1

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.
Sign up to request clarification or add additional context in comments.

1 Comment

non-static means "not declared with static", i.e. automatic storage duration variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.