Sunday, 15 May 2011

c++ - Global objects are inherently unsafe? -



c++ - Global objects are inherently unsafe? -

i know order of initialization of static variables defined in different translation units (e.g. different cpp/lib/dll/so files) undefined. mean behavior of next programme not defined?

#include <vector> std::vector<int> v; int main() { v.push_back(1); }

edit: here used stl vector example. object of other "3rd party" class. such wouldn't know if object initialized via other global variable. means in c++ not safe create single global object nontrivial constructor. right?

no, because when utilize v in main, defined. static initialization phase takes place before utilize v in main ...

the problem arise if utilize 2 globals in different translation units , there dependency between two. see c++ faq lite explanation. next items in faq explains how avoid 'fiasco'.

the problem of static initialization made globals worse in c++ in other language. library writers know problem , avoid static order initialization fiasco. , if not, if library spread, nail problem and, hope, prepare it. 3rd party libs not written, can libraries written in company ignorant new c++ programmer ...

so, yes, unsafe, you're right. , in c++ avoid globals more in other languages !

note: columbo pointed out standard not not v defined before entering main (see answer). no practical difference in instance.

c++

No comments:

Post a Comment