E.19:如果无法选择适当的资源句柄,使用final_action表现清除处理
finally is less verbose and harder to get wrong than try/catch.
和try/catch比起来,finally更加简练并不容易出错。
Example(示例)
void f(int n)
{
void* p = malloc(n);
auto _ = finally([p] { free(p); });
// ...
}
finally is not as messy as try/catch, but it is still ad-hoc. Prefer proper resource management objects. Consider finally a last resort.
finally不像try/catch那样凌乱,然仍然是针对具体问题的特殊对策。使用适当的资源管理对象的方式更好。将finally视为最后一招。
Note(注意)
Use of finally is a systematic and reasonably clean alternative to the old goto exit; technique for dealing with cleanup where resource management is not systematic.
使用finally一种系统化、合理化的代替既有代码中goto exit的方式。使用这个技术可以处理资源没有被系统化管理的问题。
Enforcement(实施建议)
Heuristic: Detect goto exit;
启发式的:检出goto exit;
关于finally
finally是gsl提供的一个支持函数,可以生成一个用户释放资源的清除动作。具体实现请参考以下链接:https://github.com/microsoft/GSL/blob/master/include/gsl/gsl_util
原文链接 https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#e19-use-a-final_action-object-to-express-cleanup-if-no-suitable-resource-handle-is-available
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有