C++核心准则E.6:使用RAII防止资源泄露
E.6: Use RAII to prevent leaks
E.6:使用RAII防止资源泄露
Reason(原因)
Leaks are typically unacceptable. Manual resource release is error-prone. RAII ("Resource Acquisition Is Initialization") is the simplest, most systematic way of preventing leaks.
资源泄露通常都是不可接受的。手动释放资源容易引发错误。RAII(“资源请求即初始化”)是防止泄露最简单,更加系统化的方式。
Example(示例)
void f1(int i) // Bad: possible leak
{
int* p = new int[12];
// ...
if (i < 17) throw Bad{"in f()", i};
// ...
}
We could carefully release the resource before the throw:
在抛出异常之前,我们必须小心地释放资源:
void f2(int i) // Clumsy and error-prone: explicit release
{
int* p = new int[12];
// ...
if (i < 17) {
delete[] p;
throw Bad{"in f()", i};
}
// ...
}
This is verbose. In larger code with multiple possible throws explicit releases become repetitive and error-prone.
代码冗长。在更大规模的,存在更多的抛出异常的可能性的代码中,显示释放资源会更加繁复和易错。
void f3(int i) // OK: resource management done by a handle (but see below)
{
auto p = make_unique<int[]>(12);
// ...
if (i < 17) throw Bad{"in f()", i};
// ...
}
Note that this works even when the throw is implicit because it happened in a called function:
需要注意的是,即使是隐式的抛出动作(因为它在调用的函数中发生),这段代码仍然可以起作用。
void f4(int i) // OK: resource management done by a handle (but see below)
{
auto p = make_unique<int[]>(12);
// ...
helper(i); // may throw
// ...
}
Unless you really need pointer semantics, use a local resource object:
除非你真的需要指针语义,否则使用一个局部的资源对象:
void f5(int i) // OK: resource management done by local object
{
vector<int> v(12);
// ...
helper(i); // may throw
// ...
}
That's even simpler and safer, and often more efficient.
这样更简单,更安全,甚至更高效。
Note(注意)
If there is no obvious resource handle and for some reason defining a proper RAII object/handle is infeasible, as a last resort, cleanup actions can be represented by a final_action object.
如果没有明显的资源句柄而且由于某种原因定义适当的RAII对象/句柄不可行,作为最有手段,可以通过一个final_actrion对象实现清理动作。
Note(注意)
But what do we do if we are writing a program where exceptions cannot be used? First challenge that assumption; there are many anti-exceptions myths around. We know of only a few good reasons:
但是,如果我们在写一个程序而无法使用异常处理时,我们应该做什么?首先挑战这个假设;存在很多反对使用异常的神话。我们只知道很少几个是正当理由:
- We are on a system so small that the exception support would eat up most of our 2K memory.
- 你正在工作的系统是如此之小,支持异常会吃掉最多2K内存(都无法承受)。
- We are in a hard-real-time system and we don't have tools that guarantee us that an exception is handled within the required time.
- 我们处在一个硬实时系统中,没有工具可以保证异常处理会在要求的时间内完成。
- We are in a system with tons of legacy code using lots of pointers in difficult-to-understand ways (in particular without a recognizable ownership strategy) so that exceptions could cause leaks.
- 我们所处的系统包含成吨的遗留代码,这些代码以难以理解的方式大量使用指针(通常没有可识别的所有权策略),因此异常可能引发泄露。
- Our implementation of the C++ exception mechanisms is unreasonably poor (slow, memory consuming, failing to work correctly for dynamically linked libraries, etc.). Complain to your implementation purveyor; if no user complains, no improvement will happen.
- 正在使用的C++实现,其异常机制超乎想象的差劲(缓慢,过多消费内存,使用动态链接库时无法工作等)。投诉你的提供者;如果没有用户投诉,就不会发生改进。
- We get fired if we challenge our manager's ancient wisdom.
- 如果我们挑战管理者的老套经验,就会被开除。
Only the first of these reasons is fundamental, so whenever possible, use exceptions to implement RAII, or design your RAII objects to never fail. When exceptions cannot be used, simulate RAII. That is, systematically check that objects are valid after construction and still release all resources in the destructor. One strategy is to add a valid() operation to every resource handle:
这些原因中只有第一个是根本性的,因此只要可能就使用异常来实现RAII,或者设计自己的RAII对象来保证永远不失败。如果无法使用异常,就模仿RAII的动作。即系统化的检查对象被构建之后的有效性和析构时会释放所有资源。一个策略是为每一个资源句柄增加一个valid操作。
void f()
{
vector<string> vs(100); // not std::vector: valid() added
if (!vs.valid()) {
// handle error or exit
}
ifstream fs("foo"); // not std::ifstream: valid() added
if (!fs.valid()) {
// handle error or exit
}
// ...
} // destructors clean up as usual
Obviously, this increases the size of the code, doesn't allow for implicit propagation of "exceptions" (valid() checks), and valid() checks can be forgotten. Prefer to use exceptions.
很显然,这回增加代码的大小,不允异常的隐式传播(通过有效性检查),而且有效性检查可以被忘记。最好使用异常。
See also: Use of noexcept
参见:使用noexcept。
Enforcement(实时建议)
原文链接https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#e6-use-raii-to-prevent-leaks
- hdu-----(1507)Uncle Tom's Inherited Land*(二分匹配)
- hdu----149850 years, 50 colors(最小覆盖点)
- hdu------1281 棋盘游戏(最小覆盖点)
- hdu-----(1179)Ollivanders: Makers of Fine Wands since 382 BC.(二分匹配)
- hdu-----(1151)Air Raid(最小覆盖路径)
- hdu-----(1150)Machine Schedule(最小覆盖点)
- 【重磅】微软Facebook联手发布AI生态系统,CNTK+Caffe2+PyTorch挑战TensorFlow
- hduoj-----(1068)Girls and Boys(二分匹配)
- 使用Django suit或Bootstrap美化admin模板
- hdu---------(1026)Ignatius and the Princess I(bfs+dfs)
- hdu-----(1113)Word Amalgamation(字符串排序)
- HDUoj-------(1128)Self Numbers
- cf------(round 2)A. Winner
- cf------(round)#1 C. Ancient Berland Circus(几何)
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- 机器学习模型调参指南(附代码)
- Flink SQL 自定义函数指南 - 以读取 GBK 编码的数据库为例
- 光照不均匀图像分割技巧1——分块阈值
- MySQL 8.0新特性 — 不可见索引
- 【小白学PyTorch】9.tensor数据结构与存储结构
- 【Python相关】jupyter平台最强插件没有之一
- 基于 OpenCV 的图像分割
- 再见,可视化!你好,Pandas!
- 40000字 Matplotlib 实操干货,真的全!
- Python自动化(二十) | 聊聊 Python 操作PDF的几种方法(合并、拆分、水印、加密)
- C语言发展史的点点滴滴
- 我写了一个R包,简化芯片的差异分析
- 【收藏】万字解析Scipy的使用技巧!
- Python 如何使用 HttpRunner 做接口自动化测试
- Python 爬虫时,高版本 App 如何进行抓包?