没有发现例外不确定的行为吗?

发布于 2025-02-06 18:05:59 字数 777 浏览 2 评论 0 原文

考虑以下代码:

#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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

装纯掩盖桑 2025-02-13 18:05:59

没有捕获异常不确定的行为?

不,明确的定义是,这将导致呼叫 std :: terminate (没有UB),尽管在呼叫之前是否在呼叫之前解开了堆栈,如 [except.thexext.ternation]

在某些情况下,

/1的例外处理被放弃,以减少细微
错误处理技术。

  • [...]
  • 当异常处理机构找不到抛出的处理程序时

/2在这种情况下,函数 std :: terminate 被调用。在
找不到匹配处理程序的情况,
实施定义了堆栈是否在
std :: terminate 被调用。
[...]不允许实现基于确定未列的过程最终会导致函数呼叫 std ::终止

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 before
std​::​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 function std​::​terminate

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文