Rather than use a global, I'd suggest it's better to use a local static. As the initialization of your vector takes place before main is entered any exceptions thrown there will not be caught by main. Say for example you have a type which when it's constructed may throw an exception:
class A {
public:
A() {
// ... code that might throw an exception
}
};
For the following initialization, the try/catch in the body of main will not catch the exception thrown by the constructor, and so your program will simply die immediately and you probably won't even be able to use a debugger to find the cause!
std::Vector<A> v(5, A()); // May throw an exception here not caught by main
int main () {
try {
// Exception for 'v' not handled here.
}
catch (...) {
}
}
An alternative approach that will catch an exception from the constructor is to use a local static - which is initialized using the technique suggested by this answer.
std::Vector<A> init (); // Returns a vector appropriately initialized
std::vector<A> & getV () {
static std::vector<A> cache = init();
return cache;
}
int main () {
try {
getV().at[0]; // First call to getV - so initialization occurs here!
}
catch (...) {
}
}