I have a vector in a header, like so:
extern std::vector g_vector;
In the associated cpp file I have this:
std::
Not sure what the issue really is, but I guess the following pattern will help solve it: define an accessor to the global variable and allocate it as a static function variable as shown below.
In the header file:
std::vector<Foo> &getGlobalVector();
In the cpp file:
std::vector<Foo> &getGlobalVector()
{
static std::vector<Foo> s_vector;
return s_vector;
}
This pattern is inspired from Andrei Alexandrescu's "generic singleton" implementation in Modern C++ design.
I've taken the habit of systematically using this pattern whenever I fell upon an existing global variable while maintaining existing applications (or in the rare occasions I actually chose to use one myself), and it may have helped in eliminating a couple of hard-to-reproduce bugs in said applications.
At any rate, this should really help avoiding any multiple-initialization or order-of-initialization related issue.
Order of initialization of global values is not defined.
Read here about the static initialization fiasco.
When you declare Bar
in a function - the g_vector
will be initialized before, because its promised to be initialized before the program runs. If Bar
is a global variable - then you have a problem.