异常的不良TypeInfo名称

Bad typeinfo name for exceptions

本文关键字:名称 TypeInfo 不良 异常      更新时间:2023-10-16

当我运行以下程序时,我会得到一个typeinfo名称。

#include <iostream>
#include <stdexcept>
#include <typeinfo>
namespace std
{
class really_out_of_range
    : public out_of_range
{
public:
    explicit really_out_of_range(const string& __s) : out_of_range(__s) {}
    explicit really_out_of_range(const char* __s)   : out_of_range(__s) {}
    virtual ~really_out_of_range() _NOEXCEPT {}
};
}
void test () noexcept(false)
{
    throw std::really_out_of_range("x > 20");
}
int main () noexcept(true)
{
    try {
        test();
    } catch (const std::exception& e) {
        std::cout << "Exception caught: " << typeid(e).name() << ": " << e.what() << 'n';
    } catch (...) {
        std::cout << "Unknown exception caughtn";
    }
}

这是输出:

捕获的例外:st19really_out_of_range:x> 20

但是,当我将test()函数上的NOExcept规范更改为true以触发std::terminate()的调用时,我会得到此输出:

libc abi.dylib:终止以未被发现的类型 std :: trume_out_of_range:x> 20

我认为std :: terminate((可能能够提供命名的无管状类型,因为它明确处理了每个标准异常类型,但这显然不是这种情况,因为它也正确处理了我上面定义的新异常类型。

所以,我的问题是为什么typeInfo名称在std::terminate()中是正确的,而当我尝试直接访问它时?或者,更重要的是,std::terminate()调用提供了什么函数?

cdhowie的评论后,我在这里找到答案:拆开std :: type_info的结果:: name

基本上,您使用#include <cxxabi.h>并致电abi::__cxa_demangle,如果您使用的是GNU。但是您必须小心内存管理。

但是,您也可以使用Boost。然后,您只需 #include <boost/core/demangle.hpp>并致电boost::core::demangle( name )