gpt4 book ai didi

c++ - C++ 运行时如何确定抛出异常的类型?

转载 作者:可可西里 更新时间:2023-11-01 17:38:42 25 4
gpt4 key购买 nike

如果我执行以下操作,运行时如何确定抛出异常的类型?它为此使用 RTTI 吗?

try
{
dostuff(); // throws something
}
catch(int e)
{
// ..
}
catch (const char * e)
{
// ..
}
catch (const myexceptiontype * e)
{
// ..
}
catch (myexceptiontype e) // is this the same as the previous handler?
{
// ..
}

另见:

How is the C++ exception handling runtime implemented?

最佳答案

与其他问题中提出的问题不同,这个问题的答案完全可以通过标准来回答。这是规则

A handler is a match for an exception object of type E if

  • The handler is of type cv T or cv T& and E and T are the same type (ignoring the top-level cv-qualifiers), or
  • the handler is of type cv T or cv T& and T is an unambiguous public base class of E, or
  • the handler is of type cv1 T* cv2 and E is a pointer type that can be converted to the type of the handler by either or both of
    • a standard pointer conversion (4.10) not involving conversions to pointers to private or protected or ambiguous classes
    • a qualification conversion

[Note: a throw-expression which is an integral constant expression of integer type that evaluates to zero does not match a handler of pointer type; that is, the null pointer constant conversions (4.10, 4.11) do not apply. ]

由于我不太确定您对标准的理解程度,因此我将不作解释,并按您的要求回答。

关于它是否使用 RTTI - 好吧,抛出的异常对象的类型是你交给 throw表达式的静态类型声明(前段时间,我很高兴在 GCC 中解决这个问题)。所以它不需要做运行时类型识别。因此,对于 g++,在 throw 出现的一侧,它会传递一个 std::type_info 对象来表示类型异常对象、对象本身和析构函数。

然后抛出并搜索帧以查找匹配的处理程序。使用在大表中找到的信息(位于名为 .eh_frame 的部分),并使用返回地址,它可以查看哪个函数负责下一个处理。该函数将安装一个个性例程,以确定它是否可以处理异常。在@PaV 链接的 Itanium C++ ABI(由 G++ 实现)中描述了整个过程(当然还有更详细的描述)。

总结一下

myexceptiontype e

const myexceptiontype *e

当然不要处理相同的类型。

关于c++ - C++ 运行时如何确定抛出异常的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/993262/

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