gpt4 book ai didi

c++ - std::exception_ptr 存储的生命周期要求

转载 作者:搜寻专家 更新时间:2023-10-31 00:30:02 37 4
gpt4 key购买 nike

给出关于来自 cppreference.comstd::exception_ptr 的示例,以下列方式缩短代码是否合法?如果所有处理都在 catch block 内完成,则无需将 std::exception_ptr 存储在外部甚至全局范围内。

#include <iostream>
#include <string>
#include <exception>
#include <stdexcept>

void handle_eptr(std::exception_ptr eptr) // passing by value is ok
{
try {
if (eptr) {
std::rethrow_exception(eptr);
}
} catch(const std::exception& e) {
std::cout << "Caught exception \"" << e.what() << "\"\n";
}
}

int main()
{
try {
std::string().at(1); // this generates an std::out_of_range
} catch(...) {
handle_eptr(std::current_exception()); // CHANGE: HANDLING THE std::exception_ptr AS R-VALUE INSIDE THE CATCH BLOCK
}
} // destructor for std::out_of_range called here, when the eptr is destructed

最佳答案

是的,程序是有效的。

来自 cppreference:

The exception object referenced by an std::exception_ptr remains valid as long as there remains at least one std::exception_ptr that is referencing it: std::exception_ptr is a shared-ownership smart pointer

在这种情况下,eptr 将确保从 std::current_exception 返回的值不会超出范围。如有疑问,请认为 std::exception_ptr 的生命周期遵循与 std::shared_ptr 相同的范围规则,因为它们都是“共享所有权智能指针”

关于c++ - std::exception_ptr 存储的生命周期要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38523864/

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