微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c 11 – 是否有相同的packaged_task :: set_exception?

我的假设是packaged_task在下面有一个承诺.如果我的任务抛出异常,我该如何将其路由到相关的未来?只有一个承诺我可以调用set_exception
– 我如何为packaged_task做同样的事情?

解决方法

std :: packaged_task有一个关联的std :: future对象,它将保存异常(或任务的结果).您可以通过调用std :: packaged_task的 get_future()成员函数来检索该未来.

这意味着在与打包任务关联的函数内部抛出异常就足以使该异常被任务的未来捕获(并在未来对象上调用get()时重新抛出).

例如:

#include <thread>
#include <future>
#include <iostream>

int main()
{
    std::packaged_task<void()> pt([] () { 
        std::cout << "Hello,"; 
        throw 42; // <== Just throw an exception...
    });

    // Retrieve the associated future...
    auto f = pt.get_future();

    // Start the task (here,in a separate thread)
    std::thread t(std::move(pt));

    try
    {
        // This will throw the exception originally thrown inside the
        // packaged task's function...
        f.get();
    }
    catch (int e)
    {
        // ...and here we have that exception
        std::cout << e;
    }

    t.join();
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐