开发者

c++ threadsafe static constructor

Given:

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

In a multi threaded setting, is it possible that new Blah() is called mo开发者_如何学JAVAre than once?

Thanks!


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜