【发布时间】:2015-12-13 19:32:35
【问题描述】:
这个
#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::exceptions?
如何在我自己的 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 行,它不会编译。
【问题讨论】:
-
@user4815162342 有趣的是,即使我使用
-fno-rtti编译,我也会得到what():行。 -
@PSkocik 在链接的文章中指出,即使在禁用 RTTI 的情况下,也使用 RTTI 的某些部分来使异常正常工作。通常这样的事情是使用编译器魔法完成的:内置和编译器特定的代码。
std::terminate在运行时库的深处实现。 libstdc++ 只是抛出当前异常并尝试捕获std::exception。源代码:searchcode.com/codesearch/view/52744421/#l-47 -
@PSkocik 是的,链接的文章明确指出了这一点。根据作者的发现,
-fno-rtti只是像typeid一样禁用了前端的功能,但是后台的异常还是使用了实现 RTTI 的机制。
标签: c++