与标准智能指针一起使用的C ++ Deleter是否有可能确定调用它的上下文?
假设释放资源可能会产生错误。
如果我的资源在堆栈展开期间被释放,那么我显然不希望我的Deleter在发生错误的情况下引发异常。但是,如果使用reset()调用Deleter,则可以将错误报告给我的代码的用户。
struct MyDeleter
{
typedef ... pointer;
void operator ()(pointer p)
{
if (release_p_failed)
{
if (throwing_exception_is_ok)
throw ...;
else
hide_error_to_not_abort;
}
}
};
例子
{
std::unique_ptr<..., MyDeleter> p{ ..., MyDeleter };
// A:
p.reset(); // User intends to handle the error. Throwing exception is ok.
// B: Leave scope and do not throw an exception in case of an error.
}
如果您担心在堆栈展开过程中引发异常,则应使用std :: uncaught_exception,例如
struct MyDeleter
{
typedef ... pointer;
void operator ()(pointer p)
{
if (release_p_failed)
{
if (!std::uncaught_exception()) // no stack unwinding in progress
throw ...;
else
hide_error_to_not_abort;
}
}
};
如果您需要从任何析构函数中抛出,这就是使用的标准习语。当然,尽管如此,这不能区分从std::unique_ptr::~std::unique_ptr
和调用std::unique_ptr::reset()
。
请注意,std::uncaught_exception
不赞成使用C ++ 17 std::uncaught_exceptions
,而将其替换为,返回当前“悬而未决”的未捕获异常数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句