`std :: terminate`如何知道特别处理`std :: exception`s?

时间:2015-12-13 19:32:35

标签: c++

这个

#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行而无法编译。

2 个答案:

答案 0 :(得分:5)

最有可能的原因是它只是尝试dynamic_cast它到std::exception,并且如果动态转换成功,则调用虚拟what()方法。

答案 1 :(得分:4)

Matched ::= Matched_If | Matched_While | Matched_For | ... | Simple_Statement ; Unmatched ::= Unmatched_If | Unmatched_While | Unmatched_For | ... ; 可以近似模拟的内容:

std::terminate

感谢revolver-ocelot让我指向了正确的方向。