为什么在FreeBSD 9上不能捕获std::bad_cast ?

Why does catching std::bad_cast not work on FreeBSD 9?

本文关键字:std bad cast FreeBSD 不能 为什么      更新时间:2023-10-16

考虑以下代码(badcast.cpp):

#include <exception>
#include <typeinfo>
#include <stdio.h>
class foo {
public:
    virtual ~foo() {}
};
class bar: public foo {
public:
    int val;
    bar(): val(123) {}
};
static void
cast_test(const foo &f) {
    try {
        const bar &b = dynamic_cast<const bar &>(f);
        printf("%dn", b.val);
    } catch (const std::bad_cast &) {
        printf("bad castn");
    }
}
int main() {
    foo f;
    cast_test(f);
    return 0;
}

FreeBSD 9.1:

$ g++ badcast.cpp -o badcast -Wall && ./badcast
terminate called after throwing an instance of 'std::bad_cast'
  what():  std::bad_cast
Abort trap (core dumped)
$ g++ badcast.cpp -o badcast -frtti -fexceptions -Wall && ./badcast
terminate called after throwing an instance of 'std::bad_cast'
  what():  std::bad_cast
Abort trap (core dumped)
$ gcc -v
Using built-in specs.
Target: amd64-undermydesk-freebsd
Configured with: FreeBSD/amd64 system compiler
Thread model: posix
gcc version 4.2.1 20070831 patched [FreeBSD]
$ uname -a
FreeBSD freebsd9 9.1-RELEASE FreeBSD 9.1-RELEASE #0 r243825: Tue Dec  4 09:23:10 UTC 2012     root@farrell.cse.buffalo.edu:/usr/obj/usr/src/sys/GENERIC  amd64

Debian Linux 6:

$ g++ badcast.cpp -o badcast -Wall && ./badcast
bad cast

OS X 10.8:

$ g++ badcast.cpp -o badcast -Wall && ./badcast
bad cast

为什么捕获bad_cast不能在FreeBSD上工作?

作为一个大胆的猜测,在FreeBSD中,您可能会使用LLVM的新libc++,而不是旧的GNU libstdc++。FreeBSD一直致力于切换到LLVM工具链,远离GNU GPL许可软件。

苹果也在朝着这个方向发展,过去我在Mac上使用libc++开发时遇到了libstdc++没有的问题(特别是使用Boost)。

你可以使用ldd来确认你要链接的库:

ldd ./badcast

如果它链接到libc++,您可能想要将错误和测试用例提交到LLVM项目中。