开发者

Unsafe to throw exceptions from statically linked C++ libraries?

I've heard that throwing exceptions in/from a C++ library could be potentially dangerous,开发者_高级运维 particularly with DLLs, and particularly if the calling code and the library are compiled with different compilers. Is there any truth to this? Is it safe as long as I stick to static libraries? Note that I am not talking about internal use of exceptions in the library only, I want to throw them deep into the calling code as well :)

Just to clarify: Say I got a compiled static library that defines class Foo like this:

class Foo
{
public:
    // Constructor
    Foo()
    {
        /* ... Do stuff ... */        
        if (stuffwentwrong)
            throw(123); // We throw an integer error code (to make it simple) 
    }
};

And some guy uses it like this:

try 
{
    Foo foo_object;
}
catch (int i)
{
    std::cout << "Oh bum. Code: " << i; 
}

Would that be safe?


With respect to GCC, there is at least one case where catching exceptions from GCC generated shared libraries can be problematic, i.e. when forgetting to export the throwable type from the shared library when symbol visibility is "hidden" by default. The GCC Visibility Wiki page goes into good detail about the issue, and how to prevent it.

I'm not sure if Windows DLLs have similar issues, but it seems likely.


and particularly if the calling code and the library are compiled with different compilers

You generally can't mix different C++ compilers that do not have compatible ABI. So, for example, you can't throw exception from library compiled with MSVC and try to catch it with GCC.

But otherwise, you generally have no issues.

Small note:

MSVC has several incompatible exception models, don't mix them.


General gotcha when it comes to DLLs and exceptions:

Don't implement the exceptions class inline in the header. You will end up with duplicate vtables and RTTI information, resulting in exceptions not being caught in the using code (due to the duplication, the exception is considered to be of another type).

The details:

http://marcmutz.wordpress.com/2010/08/04/fun-with-exceptions/


Your example you gave should work fine, however with DLLs, if you happen to throw a heap allocated exception, you will crash if the consumer of the DLL attempts to free the heap allocated exception.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜