Consider the following code:
#include <iostream>
class Widget {
public:
~Widget() {
std::cout << "Destructor Called!";
}
};
void doStuff() {
Widget w;
throw 1;
}
int main() {
doStuff();
}
Because the exception is not caught in main, the compiler can arrange for the program to call terminate immediately after the throw
with ~Widget
not called.
Since the standard does not specify whether or not the destructors are called, is this undefined behavior?
Note: The example is from this CppCon 2015 talk by Fedor Pikus.
Edit: This question asks about the compiler's freedom for destructor elision, however it is in a special, different situation. The answer to that question does not apply to this question.
CodePudding user response:
Is not catching an exception undefined behavior?
No, it is well-defined that this will result in a call to std::terminate
(with no UB), albeit whether the stack is unwound before the call is implementation-defined, as per [except.terminate]:
/1 In some situations exception handling is abandoned for less subtle error handling techniques.
- [...]
- when the exception handling mechanism cannot find a handler for a thrown exception ([except.handle]), or
/2 In such cases, the function
std::terminate
is called. In the situation where no matching handler is found, it is implementation-defined whether or not the stack is unwound beforestd::terminate
is called. [...] An implementation is not permitted to finish stack unwinding prematurely based on a determination that the unwind process will eventually cause a call to the functionstd::terminate