给出 cppreference.com 中有关 std::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/