I have a vector in a header, like so:
extern std::vector<Foo> g_vector;
In the associated cpp file I have this:
std::vector<Foo> g_vector;
I also have a class Bar
, and in it's constructor it will add some stuff to g_vector
, like so:
Bar::Bar(/* stuff */)
{
// do things
std::cout << g_vector.size() << std::endl;
g_vector.push_back(somefoo);
std::cout << g_vector.size() << std::endl;
}
If I declare a Bar
inside a function, like a sane person, it appears to work fine. However, if I want to declare a Bar
outside of a function, weird things happen. For example, I have a Bar
declared in MyFile1.cpp and in MyFile2.cpp, and because of my cout statements in Bar I can see the Foo
get pushed into the vector, but when the next Bar
runs its constructor the vector's size is 0 again. In other words, my output is
0
1
0
1
What gives? Just to be extra double sure, I also tried printing out &g_vector
to make sure it was actually push_back
ing into the right vector, and the addresses all match. For what it's worth, it doesn't matter what order these things go in to the vector. I'm not concerned with the initialization order or anything.