考虑以下代码:
#include <iostream>
class Widget {
public:
~Widget() {
std::cout << "Destructor Called!";
}
};
void doStuff() {
Widget w;
throw 1;
}
int main() {
doStuff();
}
由于未在MAIN中捕获异常,因此编译器 can 以 throw
使用 〜Widget 未调用。
由于该标准未指定毁灭者是否称为这种不确定的行为?
注意:该示例来自 this cppcon 2015 Talk by table 2015 Fedor Pikus。
编辑: 这个问题编译器的自由驱动器弹性,但是处于一种特殊的,不同的情况。该问题的答案不适用于此问题。
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.
发布评论
评论(1)
不,明确的定义是,这将导致呼叫
std :: terminate
(没有UB),尽管在呼叫之前是否在呼叫之前解开了堆栈,如 [except.thexext.ternation] :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]: