C ++ static constructor threadsafe

Given:

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

In multi-threaded setup, is it possible that the new Blah () is called more than once?

Thanks!

+4
source share
3 answers

The C ++ standard does not guarantee the security of static initialization streams - you should consider static initialization as requiring explicit synchronization.

Quote Alexander Gessler gives:

If the control enters the declaration at the same time while the object is initialized, simultaneous execution will wait for completion

from a draft C ++ 0x and does not reflect the current C ++ standard or the behavior of many C ++ compilers.

In the current C ++ standard, this passage states:

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

+4
source

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

6.7 Declaration

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

+2
source

EDIT: this refers to a C ++ 0x project.

Quoting the standard (6.7-4):

If the control enters the declaration at the same time as the object is initializing, simultaneous execution should wait for the initialization to complete

As far as I understand, static initialization is similar to thread safe.

0
source

Source: https://habr.com/ru/post/1301571/


All Articles