前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则R.12:立即将显式分配的资源交给资源管理对象​

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

作者头像
面向对象思考
发布2020-03-31 18:11:42
2660
发布2020-03-31 18:11:42
举报
文章被收录于专栏:C++核心准则原文翻译

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(反面示例)

代码语言:javascript
复制
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(示例)

代码语言:javascript
复制
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.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r12-immediately-give-the-result-of-an-explicit-resource-allocation-to-a-manager-object

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-03-29,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • R.12: Immediately give the result of an explicit resource allocation to a manager object
  • Reason(原因)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档