前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则R.1: 使用资源句柄自动管理资源并RAII(资源获取即初始化)

C++核心准则R.1: 使用资源句柄自动管理资源并RAII(资源获取即初始化)

作者头像
面向对象思考
发布2020-03-25 17:05:17
7220
发布2020-03-25 17:05:17
举报
文章被收录于专栏:C++核心准则原文翻译

R.1: Manage resources automatically using resource handles and RAII (Resource Acquisition Is Initialization) R.1: 使用资源句柄自动管理资源并RAII(资源获取即初始化)

Reason(原因)

To avoid leaks and the complexity of manual resource management. C++'s language-enforced constructor/destructor symmetry mirrors the symmetry inherent in resource acquire/release function pairs such as fopen/fclose, lock/unlock, and new/delete. Whenever you deal with a resource that needs paired acquire/release function calls, encapsulate that resource in an object that enforces pairing for you -- acquire the resource in its constructor, and release it in its destructor.

避免手动管理资源时发生泄露和复杂性。C++语言鼓励构造函数/析构函数的对称性映射资源确保/释放函数对中包含的本质的对称性。这些函数对包括fopen/fclose,lock/unlock,new/deletre等。无论什么时候,你处理一个需要成对调用申请/释放函数时,用一个强制进行成对操作的对象封装资源--在它的构造函数中申请资源,在它的析构函数中释放资源。

Example, bad(反面示例)

Consider(考虑如下代码):

代码语言:javascript
复制
void send(X* x, cstring_span destination)
{
    auto port = open_port(destination);
    my_mutex.lock();
    // ...
    send(port, x);
    // ...
    my_mutex.unlock();
    close_port(port);
    delete x;
}

In this code, you have to remember to unlock, close_port, and delete on all paths, and do each exactly once. Further, if any of the code marked ... throws an exception, then x is leaked and my_mutex remains locked.

在这段代码中,你必须记得在所有路径上unlock,close_port和delete,而且确切地只做一次。另外,如果任何一处标有...的代码抛出了异常,那么x就会泄露,my_mutex会保持锁定。

Example(示例)

Consider(考虑):

代码语言:javascript
复制
void send(unique_ptr<X> x, cstring_span destination)  // x owns the X
{
    Port port{destination};            // port owns the PortHandle
    lock_guard<mutex> guard{my_mutex}; // guard owns the lock
    // ...
    send(port, x);
    // ...
} // automatically unlocks my_mutex and deletes the pointer in x

Now all resource cleanup is automatic, performed once on all paths whether or not there is an exception. As a bonus, the function now advertises that it takes over ownership of the pointer.

现在所有的资源清除都是自动的,在每条路径上执行一次。无论是否存在异常。作为额外的奖励,这个函数对外宣称它负责资源的所有权。

What is Port? A handy wrapper that encapsulates the resource:

什么是Port?一个封装资源的便利的容器。

代码语言:javascript
复制
class Port {
    PortHandle port;
public:
    Port(cstring_span destination) : port{open_port(destination)} { }
    ~Port() { close_port(port); }
    operator PortHandle() { return port; }

    // port handles can't usually be cloned, so disable copying and assignment if necessary
    Port(const Port&) = delete;
    Port& operator=(const Port&) = delete;
};
Note(注意)

Where a resource is "ill-behaved" in that it isn't represented as a class with a destructor, wrap it in a class or use finally

当资源由于没有表现为一个带有虚构函数的类而存在"病态行为",用一个类封装它或者使用finally。

See also: RAII

参照:RAII

参考:

Finally:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Re-finally

RAII:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rr-raii

原文链接:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r1-manage-resources-automatically-using-resource-handles-and-raii-resource-acquisition-is-initialization


觉得本文有帮助?请分享给更多人。

关注【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • R.1: Manage resources automatically using resource handles and RAII (Resource Acquisition Is Initialization) R.1: 使用资源句柄自动管理资源并RAII(资源获取即初始化)
  • Reason(原因)
    • Note(注意)
    相关产品与服务
    容器服务
    腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档