When an exception is thrown, the exception object operand of the
throw expression is copied into a temporary object that is used to initialize the handler. The C++ Standard, [except.throw], paragraph 3 [ISO/IEC 14882-2014], in part, states the following:
Throwing an exception copy-initializes a temporary object, called the exception object. The temporary is an lvalue and is used to initialize the variable declared in the matching handler.
If the copy constructor for the exception object type throws during the copy initialization,
std::terminate() is called, which can result in undefined behavior. For more information on implicitly calling
std::terminate(), see ERR50-CPP. Do not abruptly terminate the program.
The copy constructor for an object thrown as an exception must be declared
noexcept, including any implicitly-defined copy constructors. Any function declared
noexcept that terminates by throwing an exception violates ERR55-CPP. Honor exception specifications.
The C++ Standard allows the copy constructor to be elided when initializing the exception object to perform the initialization if a temporary is thrown. Many modern compiler implementations make use of both optimization techniques. However, the copy constructor for an exception object still must not throw an exception because compilers are not required to elide the copy constructor call in all situations, and common implementations of
std::exception_ptr will call a copy constructor even if it can be elided from a
Noncompliant Code Example
In this noncompliant code example, an exception of type
S is thrown in
f(). However, because
S has a
std::string data member, and the copy constructor for
std::string is not declared
noexcept, the implicitly-defined copy constructor for
S is also not declared to be
noexcept. In low-memory situations, the copy constructor for
std::string may be unable to allocate sufficient memory to complete the copy operation, resulting in a
std::bad_alloc exception being thrown.
This compliant solution assumes that the type of the exception object can inherit from
std::runtime_error, or that type can be used directly. Unlike
std::runtime_error object is required to correctly handle an arbitrary-length error message that is exception safe and guarantees the copy constructor will not throw [ISO/IEC 14882-2014].
If the exception type cannot be modified to inherit from
std::runtime_error, a data member of that type is a legitimate implementation strategy, as shown in this compliant solution.
|Checked by |
Exception objects must be nothrow copy constructible
|SEI CERT C++ Coding Standard|
Subclause 15.1, "Throwing an Exception"