gpt4 book ai didi

c++ - 使用 std::make_exception_ptr 的奇怪行为

转载 作者:行者123 更新时间:2023-11-27 22:56:53 28 4
gpt4 key购买 nike

我想知道为什么 std::current_exception() 在这种情况下的工作方式不同:

std::exception_ptr e, e2;
try {
std::string("abcd").substr(42);
} catch(std::exception &ex) {
std::cerr << "(1) Exception: " << ex.what() << std::endl;
e = std::current_exception();
e2 = std::make_exception_ptr(ex);
}
handle_exception(e);
handle_exception(e2);

而 handle_exception 打印异常:

void handle_exception(std::exception_ptr e)
{
try {
if (e)
std::rethrow_exception(e);
} catch(const std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
}

输出如下:

(1) Exception: basic_string::substr: __pos (which is 42) > this->size() (which is 4)
(2) Exception: basic_string::substr: __pos (which is 42) > this->size() (which is 4)
(3) Exception: std::exception

但是我希望得到以下输出:

(1) Exception: basic_string::substr: __pos (which is 42) > this->size() (which is 4)
(2) Exception: basic_string::substr: __pos (which is 42) > this->size() (which is 4)
(3) Exception: basic_string::substr: __pos (which is 42) > this->size() (which is 4)

我在这里错过了什么?

最佳答案

std::make_exception_ptr() 按值获取其参数。这意味着复制或就地构建。

您正在复制 std::exception(即切片)

关于c++ - 使用 std::make_exception_ptr 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31925998/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com