views:

78

answers:

3

Given:

void getBlah() {
  static Blah* blah = new Blah();
  return blah;
}

In a multi threaded setting, is it possible that new Blah() is called more than once?

Thanks!

A: 

EDIT: This pertains to the C++0x draft.

Quoting the standard (6.7-4):

If control enters the declaration concurrently while the object is being initialized, the concurrent execution shall wait for completion of the initialization

To my understanding, static initialization like this is thread-safe.

Alexander Gessler
That's a quote from the C++0x draft.
Joe Gauterin
Yes, indeed it's from the cpp0x draft. So I assume this line is missing in the current standard?
Alexander Gessler
I've added the text from the current standard to my answer.
Joe Gauterin
Why is this response down voted? I find it perfectly useful, even if it's citing a future draft.
anon
+2  A: 

No. But note that the pointer to Blah is static.

6.7 Declaration statement

4 [...] Otherwise such an object is initialized the first time control passes through its declaration; such an object is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration

dirkgently
+4  A: 

The C++ standard makes no guarantee about the thread safety of static initializations - you should treat the static initialization as requiring explicit synchronisation.

The quote Alexander Gessler gives:

If control enters the declaration concurrently while the object is being initialized, the concurrent execution shall wait for completion of the initialization

is from the C++0x draft, and doesn't reflect the current C++ standard or the behaviour of many C++ compilers.

In the current C++ standard, that passage reads:

If control re-enters the declaration (recursively) while the object is being initialized, the behaviour is undefined

Joe Gauterin
Even the C++0x draft has an example highlighting this very point at the end of para 4 of 6.7.
dirkgently
Thanks for the clarification.
Alexander Gessler