gpt4 book ai didi

c++ - `std::terminate` 是怎么知道要特殊对待 `std::exception` 的呢?

转载 作者:太空狗 更新时间:2023-10-29 23:44:12 25 4
gpt4 key购买 nike

这个

#include <stdexcept>
struct A /*: public std::exception*/ {
const char* what() const noexcept { return "this is A"; }
};
int main(){
throw A{};
return 0;
}

给我(在 stderr 上):

terminate called after throwing an instance of 'A'
Aborted (core dumped)

如果我取消评论,死亡消息将变为:

terminate called after throwing an instance of 'A'
what(): this is A
Aborted (core dumped)

std::terminate 如何知道如何特殊处理 std::exception

如何在我自己的 set_terminate 中模拟它?我试过了

//...
int main(){
std::set_terminate([](){
printf("exception thrown\n");
std::exception_ptr eptr = std::current_exception();
std::exception* ptr = dynamic_cast<std::exception*>(eptr);
if (ptr)
puts(ptr->what());
});
throw A{};
}

但由于 dynamic_cast 行,它不会编译。

最佳答案

最有可能是因为它只是尝试将其dynamic_caststd::exception,并调用虚拟what() 方法,如果动态转换成功。

关于c++ - `std::terminate` 是怎么知道要特殊对待 `std::exception` 的呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34255368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com