How lazy can C++ global initialization be?

假装没事ソ 提交于 2019-12-04 02:43:11

The standard has the following in 3.6.2/3:

It is implementation-defined 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.

But o Of course you can never officially tell when the initialization takes place since the initialization will occur before you access the variable! as follows:

// t1.cc
#include <iostream>
int i1 = 0;

int main () {
  std::cout << i1 << std::endl

// t2.cc
extern int i1;
int i2 = ++i1;

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:

static int ItsDllVar = 1;
int EXPORTED_FUNCTION() { return ItsDllVar; }

In application:

static int AppVar1 = 2;
static int AppVar2 = EXPORTED_FUNCTION() + AppVar1;

So according to static initializing AppVar2 gets 1+2=3

Lazy initialization applicable for local static variables (regardless of DLL)

int f()
{
    static int local_i = 5;//it get's 5 only after visiting f()
    return local_i;
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!