本文介绍了怎样的std ::异步"店"任意例外?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解怎么可能为的std ::异步来存储任何例外,而不是只是一些从的std ::而得例外。我玩与周围的code以下

I am not able to understand how is it possible for std::async to store any exception, not just something derived from std::exception. I played around with the code below

#include <iostream>
#include <future>
#include <chrono>

void f()
{
    std::cout << "\t\tIn f() we throw an exception" << std::endl;
    throw 1; // throw an int
}

int main()
{
    std::future<void> fut = std::async(std::launch::async, f);
    std::cout << "Main thread sleeping 1s..." << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(1)); // sleep one second
    std::cout << "Main thread waking up" << std::endl;
    try
    {
        fut.get();
    }
    catch(...)
    {
        std::cout << "We caught an exception!" << std::endl;
        throw; // rethrow
    }
}

我启动 F()异步,然后抛出一个 INT ˚F。奇妙的是,这个 INT 被捕获并通过的std ::异步回到未来存储。据我所知,是可能的赶上(...)的例外的std ::异步,但怎么能后者的IT卖场不知道的异常类型?唯一的例外是不是一些基类派生的(在这种情况下,一个也许会克隆通过某些基础::克隆它),但可以是任何异常。可我们却不知何故神奇地演绎的异常类型?

I launch f() asynchronously, then throw an int inside f. Magically, this int is caught and stored by the future returned by std::async. I understand that is possible to catch(...) the exception in std::async, but how can the latter store it without knowing the exception type? The exception is not derived from some base class (in this case one perhaps can "clone" it via some Base::clone), but can be any exception. Can we somehow magically "deduce" the exception type?

要总结,我的问题是:

我们如何可以存储对象中的任意例外,然后在一段时间后重新抛出它,不知道的异常类型?

How can we store an arbitrary exception inside an object then re-throw it at some later time, without knowing the exception type?

推荐答案

的std ::异步可以在性病的基础上实现::线程的std :: packaged_task

的std :: packaged_task 可以实现(部分)在的std :: exception_ptr 的顶部和相关的功能(除了线程退出就绪功能)。

std::packaged_task could be implemented (partly) on top of std::exception_ptr and related function (except that thread-exit ready function).

的std :: exception_ptr 及相关功能无法在C ++编写。

std::exception_ptr and related functions cannot be written in C++.

这篇关于怎样的std ::异步&QUOT;店&QUOT;任意例外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 02:18