boost::packaged_task生成的future是否抛出错误的异常

Does the future generated from boost::packaged_task throw wrong exception?

本文关键字:是否 错误 异常 future 出错 packaged task boost      更新时间:2023-10-16

我发现boost::packaged_task和std::package d_task之间有明显不同的行为。我测试了boost版本1.55和1.56,c++11编译器是Visual Studio 2013和gcc(XCode中)。

也就是说,由packaged_task::get_future()生成的future的调用get()发出不同的异常。

这是我的简单代码:

#include <boost/thread/future.hpp>
#include <future>
#include <iostream>
struct my_error {};
void throw_something()
{
    throw my_error();
}
int main()
{
    typedef boost::packaged_task<void> packaged_task;
    packaged_task task(throw_something);
    auto fu = task.get_future();
    task();
    try {
        fu.get();
        std::cout << "no exception" << std::endl;
    }
    catch (const my_error&) {
        std::cout << "catch my_error" << std::endl;
    } catch (const std::exception &e) {
        std::cout << "catch std::exception: " << e.what() << std::endl;
    } catch (...) {
        std::cout << "catch unknown error" << std::endl;
    }
    std::system("pause");
    return 0;
}

在Visual Studio 2013中,结果是:catch std::exception:未知异常

在gcc中(在XCode中)是:catch-std::exception:std::exception

但是,如果我将packaged_task的类型更改为Visual Studio 2013或gcc提供的c++11,那就是:

 typedef std::packaged_task<void()> packaged_task;

结果变得不同:捕获my_error

我认为std::packaged_task工作正常,因为我可以捕捉到真正的类型。我是否滥用boost::packaged_task

一个关键区别可能是标准库package_task可能是静态链接的,而boost::thread版本是动态链接的。

跨越动态库边界抛出异常可能并不总是有效的,尤其是当源代码不是用完全相同的编译器选项编译时。

你可以

  • 检查库是否使用相同的标志编译
  • 使用Boost线程库的静态版本(Boost_Thread_static、Boost_ALL_NO_LIB可能与快速搜索有关),另请参阅http://www.boost.org/boost-build2/doc/html/bbv2/tutorial/linkage.html