C++核心准则E.19:如果无法选择适当的资源句柄,使用final_action表现清除处理​

时间:2022-07-22
本文章向大家介绍C++核心准则E.19:如果无法选择适当的资源句柄,使用final_action表现清除处理​,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

E.19: Use a final_action object to express cleanup if no suitable resource handle is available

E.19:如果无法选择适当的资源句柄,使用final_action表现清除处理

Reason(原因)

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); });
    // ...
}
Note(注意)

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