在不使用std :: current_exception的情况下设置异常

发布于 2025-02-03 21:48:08 字数 940 浏览 2 评论 0原文

c ++参考有关set_expection methot ,该示例使用std :: Current_exception。为此,您必须投掷并捕捉异常:

    std::thread t([&p]{
        try {
            // code that may throw
            throw std::runtime_error("Example");
        } catch(...) {
            try {
                // store anything thrown in the promise
                p.set_exception(std::current_exception());
                // or throw a custom exception instead
                // p.set_exception(std::make_exception_ptr(MyException("mine")));
            } catch(...) {} // set_exception() may throw too
        }
    });

这种投掷和捕捉显然很乏味,但是该方法接受std :: exception_ptr。我想知道是否可以直接设置特定的异常。我想问题是,如果我们将指针传递给其地址并分配新的异常对象,将会出现终生问题。有办法吗?

In C++ reference regarding the set_exception method , the example uses std::current_exception. To do that you have to throw and catch your exception:

    std::thread t([&p]{
        try {
            // code that may throw
            throw std::runtime_error("Example");
        } catch(...) {
            try {
                // store anything thrown in the promise
                p.set_exception(std::current_exception());
                // or throw a custom exception instead
                // p.set_exception(std::make_exception_ptr(MyException("mine")));
            } catch(...) {} // set_exception() may throw too
        }
    });

This throwing and catching is obviously tedious, but the method accepts a std::exception_ptr. I was wondering whether it's possible to set a specific exception directly. I imagine the problem would be that a local exception object would have lifetime issues if we pass around a pointer to its address and allocating a new exception object would leave memory leaks. Is there a way ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文