I'm used to thinking of all initialization of globals/static-class-members as happening before the first line of main(). But I recently read somewhere that the standard allows initialization to happen later to "assist with dynamic loading of modules." I could see this being true when dynamic linking: I wouldn't expect a global initialized in a library to be initialized before I dlopen'ed the library. However, within a grouping of statically linked together translation units (my app's direct .o files) I would find this behavior very unintuitive. Does this only happen lazily when dynamically linking or can it happen at any time? (or was what I read just wrong? ;)
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
The standard has the following in 3.6.2/3:
But oOf course you cannever officiallytell when the initialization takes placesince the initialization will occur before you access the variable!as follows:I can conform that g++ 4.2.4 at least appears to perform the initialization of 'i2' before main.
The problem that one wanted to solve with that rule is the one of dynamic loading. The allowance isn't restricted to dynamic loading and formally could happen for other cases. I don't know an implementation which use it for anything else than dynamic loading.
Let's review a pseudocode:
In DLL:
In application:
So according to static initializing AppVar2 gets 1+2=3
Lazy initialization applicable for local static variables (regardless of DLL)
I think this is what happened in my case with g++ 4.7 and CMake (not sure if this is a relevant detail regarding CMake). I have a code that registers a function in the factory. It relies on the constructor calling from a globally initialized variable.
When this code was in the statically linked library the initialization didn't happen! It is now working fine, when I moved it to the object files that linked directly (i.e., they are not combined into a library first).
So, I suspect that you are correct.