C++核心准则R.12:立即将显式分配的资源交给资源管理对象

R.12: Immediately give the result of an explicit resource allocation to a manager objectR.12:立即将显式分配的资源交给资源管理对象Reason(原因

R.12: Immediately give the result of an explicit resource allocation to a manager object

R.12:立即将显式分配的资源交给资源管理对象

 

Reason(原因)

If you don't, an exception or a return may lead to a leak.

如果不这样做,发生异常或者返回操作时可能会引发泄露。

 

Example, bad(反面示例)

void f(const string& name)
{
    FILE* f = fopen(name, "r");            // open the file
    vector<char> buf(1024);
    auto _ = finally([f] { fclose(f); });  // remember to close the file
    // ...
}

The allocation of buf may fail and leak the file handle.

如果分配buffer失败(抛出异常,译者注)就会导致文件句柄的泄露。

 

Example(示例)

void f(const string& name)
{
    ifstream f{name};   // open the file
    vector<char> buf(1024);
    // ...
}

The use of the file handle (in ifstream) is simple, efficient, and safe.

(使用ifstream管理)文件句柄的用法简单、高效而且安全。

 

Enforcement(实施建议)

  • Flag explicit allocations used to initialize pointers (problem: how many direct resource allocations can we recognize?)

  • 标记使用显式分配的资源初始化指针的情况(问题是:我们能够识别出多少直接分配资源的情况?)

 

原文链接:

https://github/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r12-immediately-give-the-result-of-an-explicit-resource-allocation-to-a-manager-object

 


 

觉得本文有帮助?欢迎点赞并分享给更多的人。

阅读更多更新文章,请关注微信公众号【面向对象思考】

发布者:admin,转转请注明出处:http://www.yc00.com/web/1754581399a5177975.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信