...
When declaring an object with static or thread storage duration, and that object is not declared within a function block scope, the type's constructor must be declared noexcept
and must comply with ERR55-CPP. Honor exception specifications. Additionally, the initializer for such a declaration, if any, must not throw an uncaught exception (including from any implicitly constructed objects that are created as a part of the initialization). If an uncaught exception is thrown before main()
is executed, or if an uncaught exception is thrown after main()
has finished executing, there are no further opportunities to handle the exception and it results in implementation-defined behavior; see . (See ERR50-CPP. Do not abruptly terminate the program for further details.)
For more information on exception specifications of destructors, see DCL57-CPP. Do not let exceptions escape from destructors or deallocation functions.
...
In this noncompliant example, the constructor of global
may throw an exception during program startup. (the The std::string
constructor accepting , which accepts a const char *
and a default allocator object, is not marked noexcept
and consequently allows all exceptions.) . This exception is not caught by the function-try-block on main()
, resulting in a call to std::terminate()
and abnormal program termination.
...
Compliant code must prevent exceptions from escaping during program startup and termination. This compliant solution avoids defining a std::string
at global namespace scope and instead uses a static const char *
:.
Code Block | ||||
---|---|---|---|---|
| ||||
static const char *global = "..."; int main() { // ... } |
...