提升共享库中的异常

boost exceptions in a shared library

本文关键字:异常 共享      更新时间:2023-10-16

>编辑:已解决。问题要良性得多 - 我有两个函数在一行代码中相互调用 - 都使用lexical_cast另一个崩溃。有趣的是,我只能通过撒上很多cout来发现这一点,因为崩溃时没有回溯,并且在调试行时,gdb 出于某种原因显示错误的lexical_cast作为罪魁祸首(我没有看到另一个,叹息(。感谢您的帮助!


我正在使用 gcc 4.1.2 和提升 1.48。我在模板函数内的共享库中有以下代码:

try {
  boost::lexical_cast<T>(s);
}
catch (...) {
  std::cout << "Caught it" << std::endl;
  throw;
}

强制转换失败,但异常未被捕获(它确实传播并终止程序,但此 catch-子句不会捕获它(。 Tlongs是等于"234a234"std::string。(我还尝试将提升包含包装在#pragma GCC visibility push(default)中,并尝试在链接时添加-shared-libgcc标志,但这没有任何作用。

不过它会变得更好。在以下两种情况下,确实会捕获异常:

try {
  throw boost::bad_lexical_cast();
}
catch (...) {
  std::cout << "Caught it" << std::endl;
  throw;
}

令人惊讶的是,这个:

try {
  boost::lexical_cast<T>(s);
  throw boost::bad_lexical_cast();
}
catch (...) {
  std::cout << "Caught it" << std::endl;
  throw;
}

关于正在发生的事情的任何想法,更重要的是如何解决这个问题?

我无法在我的机器上重现,但我使用的是不同的编译器

gcc version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.1.00)

我使用以下作为测试:

#include <iostream>
#include <boost/lexical_cast.hpp>
#include <string>
#include <exception>
using namespace std;
template<typename T>
T printLexicalCast(const std::string& s){
    T t;
    try {
         t = boost::lexical_cast<T>(s);
         cout << "cast is [" << t << "] from string [" << s << "]" << endl;
    }
    catch (const boost::bad_lexical_cast& e ) {
      std::cout << "Caught bad lexical cast with error " << e.what() << std::endl;
    }
    catch( ... ){
        std::cout << "Unknown exception caught!" << endl;
    }
    return t;
}   

int main(int argc, char *argv[]) {
    std::string badString("234a234");
    long l1 = printLexicalCast<long>(badString); //exception

    std::string goodString("123456");
    long l2 = printLexicalCast<long>(goodString); 
    return 0;
}

我得到以下输出:

Caught bad lexical cast with error bad lexical cast: source type value could not be interpreted as target
cast is [123456] from string [123456]

如果我删除bad_lexical_cast抓住包罗万象的作品。

Unknown exception caught!
cast is [123456] from string [123456]

也许这只是一个编译器错误? 我在提升用户列表中找到了这个

http://boost.2283326.n4.nabble.com/conversion-lexical-cast-doesn-t-throw-td2593967.html

如果BOOST_NO_EXCEPTIONS在某处被定义,就会发生这种情况。