Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global objects are inherently unsafe?

Tags:

c++

I know that the order of initialization of static variables defined in different translation units (e.g. different cpp/lib/dll/so files) is undefined. Does it mean that the behavior of following program is not well defined?

#include <vector>

std::vector<int> v;

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

EDIT: Here I used STL vector as an example. But it could be an object of any other "3rd party" class. As such we wouldn't know if that object initialized via some other global variable. This means that in C++ it not safe to create even a single global object with nontrivial constructor. Right?

like image 551
quantum_well Avatar asked Dec 06 '22 23:12

quantum_well


1 Answers

No, because when you use v in main, it is perfectly defined. The static initialization phase takes place before you use v in main ...

The problem arise if you use 2 globals in different translation units and there is a dependency between the two. See this C++ FAQ lite for an explanation. The next items in the FAQ explains how to avoid the 'fiasco'.

The problem of static initialization made globals worse in C++ than in any other language. Good library writers know the problem and avoid the static order initialization fiasco. And even if not, if the library is well spread, someone will hit the problem and, I hope, fix it. But 3rd party libs are not always well written, they can be libraries written in your company by an ignorant new to C++ programmer ...

So, yes, it is unsafe, you're right. And in C++ avoid globals even more than in other languages !

Note: Columbo as pointed out that the standard does not not exactly say that v is defined before entering main (see his answer). No practical difference in your instance.

like image 95
neuro Avatar answered Dec 21 '22 23:12

neuro