可能重复:
C++异常会通过C代码安全传播吗?
如果您有c代码,例如png lib,您自己的io处理程序是用c ++编写的,并且由于某些io错误而抛出异常.让它通过c代码并在c代码之外捕获它是否可以?我知道必须注意内存泄漏,但通常所有结构都要预先分配.
完全取决于编译器是否可行.没有一种语言标准可以明显地说出其他语言应该做什么.
在最好的情况下,异常将传递C代码并返回到下一个C++级别,同时可能泄漏任何动态分配的C结构.在不太好的情况下,它会崩溃和燃烧!
一种可能性当然是将C代码编译为C++,同时还检查它是异常中性的.
您的问题的答案是实现定义的.
对于GCC,正如@Kerrek所说,编译C代码-fexceptions将确保在通过C代码抛出异常时运行时保持一致.(需要注意的是现代的例外机制不只是通过了setjmp/longjmp的实现;它们实际上是由框架,以妥善处理析构函数和try/catch块展开堆栈帧).
但是,C代码本身可能不会期望通过它抛出异常.很多C代码都是这样编写的:
acquire a resource
do some stuff
release resource
Run Code Online (Sandbox Code Playgroud)
这里"获取资源"可能意味着malloc,或pthread_mutex_lock,或fopen.如果你的C++代码是"做一些东西"的一部分,它会抛出异常,那么......哎呀.
资源泄漏不是唯一的问题; 所以正确性是一般的.想像:
subtract $100 from savings account
add $100 to checking account
Run Code Online (Sandbox Code Playgroud)
现在假设在第一步完成后但在第二步完成之前抛出异常.
简而言之,虽然您的实现可能提供了一种让您通过C代码抛出异常的方法,但这是一个坏主意,除非您还编写了C代码,知道可能引发异常的确切位置.
你的C++代码是可以的,如果它是:
如果符合以下条件,您的C或C++代码就可以了:
使用C++异常支持编译的代码添加了特殊的挂钩,以便在抛出异常时清除并且不会在该范围中捕获.在堆栈上分配的C++对象将调用其析构函数.
抛出异常时在C(或C++中无异常支持)中回收的唯一资源是在每个堆栈帧中分配的空间.
GCC手册的这一部分非常有用:
-fexceptions
Enable exception handling. Generates extra code needed to
propagate exceptions. For some targets, this implies GCC will
generate frame unwind information for all functions, which can
produce significant data size overhead, although it does not affect
execution. If you do not specify this option, GCC will enable it
by default for languages like C++ which normally require exception
handling, and disable it for languages like C that do not normally
require it. However, you may need to enable this option when
compiling C code that needs to interoperate properly with exception
handlers written in C++. You may also wish to disable this option
if you are compiling older C++ programs that don't use exception
handling.
| 归档时间: |
|
| 查看次数: |
3181 次 |
| 最近记录: |