Are global objects inherently unsafe?

I know that the initialization order of static variables defined in different translation units (for example different cpp / lib / dll / so files) is undefined. Does this mean that the behavior of the next program is poorly defined?

#include <vector>

std::vector<int> v;

int main()
{
    v.push_back(1);
}

      

EDIT: I used an STL vector as an example. But it can be an object of any other "third party" class. Thus, we would not know if this object was initialized through some other global variable. This means that in C ++ it is not safe to create even one global object with a non-trivial constructor. Right?

+3


source to share


3 answers


No, because when you use v in main it is perfectly defined. The static initialization phase occurs before using v in the main ...

The problem arises if you use 2 globals in different translation units and there is a dependency between them. See the C ++ FAQ lite for an explanation. The following points in the FAQ explain how to avoid fiasco.

The static initialization problem made globals worse in C ++ than in any other language. Good librarians know the problem and avoid the static order initialization fiasco. And even if not, if the library is well distributed, someone will run into a problem and hopefully fix it. But third party libraries are not always well written, they might be libraries written in your company by an unfamiliar newbie C ++ programmer ...



So yes, it is not safe, you are right. And avoid globals even more in C ++ than in other languages!

Note. Columbo, pointing out that the standard is not quite accurate about v being defined before entering the main one (see his answer). There is no practical difference in your case.

+8


source


It is listed in [basic.start.init] / 4:

It is implementation-defined whether dynamic initialization is a non-local variable with static storage duration performed prior to the first statement of the main. If initialization is deferred until some point in time after the first statement of main, this must occur before the first use of odr (3.2) of any function or variable defined in the same translation unit as the variable to be initialized.



Therefore, it v

is defined what is initialized before its first use in any function of this translation unit, including main

. This means that in this particular program it is v

initialized before the first statement main

.

static initialization order fiasco occurs when multiple variables in different translation units depend on their relative initialization order; Initializations can be indefinitely sequenced relative to each other, depending on their initialization.

+6


source


Since there is only one global object, there can only be one order of initialization, and so there is no problem.

0


source







All Articles