如何实现C ++异常处理运行时? [英] How is the C++ exception handling runtime implemented?

查看:97
本文介绍了如何实现C ++异常处理运行时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C ++异常处理机制的工作原理很感兴趣。具体来说,异常对象存储在哪里,以及它是如何传播通过几个范围,直到它被捕获?它存储在一些全球区域?



因为这可能是编译器特定的,可以有人在g ++编译器套件的上下文中解释这个问题?



异常对象本身是在一个函数中创建的对象,在其调用者中被破坏。因此,在堆栈上创建对象通常是不可行的。另一方面,许多异常对象不是很大。 Ergo,如果实际需要一个更大的异常对象,那么可以创建一个32字节的缓冲区并溢出到heap。



对于控制的实际传输,存在两种策略。一个是在堆栈本身中记录足够的信息以展开堆栈。这基本上是运行的析构函数列表和可能捕获异常的异常处理程序。当异常发生时,运行堆栈执行那些析构函数,直到找到匹配的catch。



第二个策略将此信息移动到堆栈外的表中。现在,当发生异常时,调用堆栈用于查找输入但未退出的范围。然后在静态表中查找它们,以确定抛出的异常将在何处处理,以及哪些析构函数在其间运行。这意味着堆栈上的异常开销较少;返回地址仍然需要。这些表是额外的数据,但编译器可以将它们放在需要加载的程序段中。


I am intrigued by how the C++ exception handling mechanism works. Specifically, where is the exception object stored and how does it propagate through several scopes until it is caught? Is it stored in some global area?

Since this could be compiler specific could somebody explain this in the context of the g++ compiler suite?

解决方案

Implementations may differ, but there are some basic ideas that follow from requirements.

The exception object itself is an object created in one function, destroyed in a caller thereof. Hence, it's typically not feasible to create the object on the stack. On the other hand, many exception objects are not very big. Ergo, one can create e.g a 32 byte buffer and overflow to heap if a bigger exception object is actually needed.

As for the actual transfer of control, two strategies exist. One is to record enough information in the stack itself to unwind the stack. This is basically a list of destructors to run and exception handlers that might catch the exception. When an exception happens, run back the stack executing those destructors until you find a matching catch.

The second strategy moves this information into tables outside the stack. Now, when an exception occurs, the call stack is used to find out which scopes are entered but not exited. Those are then looked up in the static tables to determine where the thrown exception will be handled, and which destructors run in between. This means there is less exception overhead on the stack; return addresses are needed anyway. The tables are extra data, but the compiler can put them in a demand-loaded segment of the program.

这篇关于如何实现C ++异常处理运行时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆