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