If a constructor throws exception, then does it make sense to have a global object of that class?

Viewed 543

I am asking this question for general coding guidelines:

class A {
  A() { ... throw 0; }
};
A obj;  // <---global

int main()
{
}

If obj throws exception in above code then, it will eventually terminate the code before main() gets called. So my question is, what guideline I should take for such scenario ? Is it ok to declare global objects for such classes or not ? Should I always refrain myself from doing so, or is it a good tendency to catch the error in the beginning itself ?

6 Answers

Like @J T have said, you can write like this:

struct S {
  S() noexcept(false);
};

S &globalS() {
  try {
    static S s;
    return s;
  } catch (...) {
    // Handle error, perhaps by logging it and gracefully terminating the application.
  }
  // Unreachable.
}

Such scenario is quite a problem, please read ERR58-CPP. Handle all exceptions thrown before main() begins executing for more detail.

Related