简体   繁体   中英

C++ Dynamic initialization - across translation units

The C++98 language standard states: (My emphasis)


3.6.2 Initialization of nonlocal objects

£1 [...] Zeroinitialization and initialization with a constant expression are collectively called static initialization; all other initialization is dynamic initialization . [...]

£3 [...] It is implementationdefined whether or not the dynamic initialization (8.5, 9.4, 12.1, 12.6.1) of an object of namespace scope is done before the first statement of main. If the initialization is deferred to some point in time after the first statement of main, it shall occur before the first use of any function or object defined in the same translation unit as the object to be initialized. [...]


In my office, we have got two interpretations of the boldface passage...

My question is: There is a class has a whole bunch of static methods and dynamically initialized static data members. Can it (or can't it) happen that static methods in this class are called from another translation unit , before dynamic initialization has been completed?

Thanks!

[Edit:]

Perhaps this boils down to the reading of "it shall occur" as:

  1. Shall have begun
  2. Shall have been completed

Can it (or can't it) happen that static methods in this class are called from another translation unit, before dynamic initialization has been completed?

The bolded passage is pretty clear, isn't it? Initialization of such data is guaranteed to happen before first use of any function or class defined in its translation unit. It doesn't matter where a function is called from . The guarantee is that initialization happens before the first use of any functions in the translation unit. Of course they may be called from another translation unit, but that doesn't make any difference. Before a function defined in this translation unit is entered, initialization must have been performed.

In other words, you're safe.

...

assuming single-threaded execution, that is. C++98 provides no guarantees in a multithreaded environment, so for a threaded application, the above guarantee typically just means that initialization will be performed by the first thread to use a function or class from this translation unit. And then you have a race condition while this initialization is being performed, where other threads might hit the partially-initialized data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM