C++析构函数,内存释放和swap操作分析
本篇内容介绍了“C++析构函数,内存释放和swap操作分析”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
创新互联建站是专业的临泉网站建设公司,临泉接单;提供成都做网站、成都网站设计,网页设计,网站设计,建网站,PHP网站建设等专业做网站服务;采用PHP框架,可快速的进行临泉网站开发网页制作和功能扩展;专业做搜索引擎喜爱的网站,专业的做网站团队,希望更多企业前来合作!
E.16:析构函数,内存释放和swap操作永远不能失败
Reason(原因)
如果析构函数、swap操作或者内存释放失败了,我们不知道如何编写可信赖的处理程序;也就是说,如果它因为异常退出或者只是没有执行要求的操作。
Example, don't(反面示例)
class Connection {
// ...
public:
~Connection() // Don't: very bad destructor
{
if (cannot_disconnect()) throw I_give_up{information};
// ...
}
};
Note(注意)
Many have tried to write reliable code violating this rule for examples, such as a network connection that "refuses to close". To the best of our knowledge nobody has found a general way of doing this. Occasionally, for very specific examples, you can get away with setting some state for future cleanup. For example, we might put a socket that does not want to close on a "bad socket" list, to be examined by a regular sweep of the system state. Every example we have seen of this is error-prone, specialized, and often buggy.
为了编写违反本规则的可信赖代码示例进行了很多尝试,例如网络链接“拒绝关闭”。即使动作所有知识,也没有人发现这么做的通用方法。偶然情况下,对于非常特殊的情况,你可以通过设定在将来清除处理时使用的某些状态。例如我们可以将不想关闭的socket放入一个“坏socket”列表中,以便用正规的系统状态清除程序进行检查。我们看到的所有相关示例都是容易出错的,特殊的,通常也有很多bug。
Note(注意)
The standard library assumes that destructors, deallocation functions (e.g., operator delete), and swap do not throw. If they do, basic standard-library invariants are broken.
标准库假设析构函数,内存释放函数(例如delete运算符),swap都不会抛出异常。如果它们异常,标准库的不变量就被破坏了。
Note(注意)
Deallocation functions, including operator delete, must be noexcept. swap functions must be noexcept. Most destructors are implicitly noexcept by default. Also, make move operations noexcept.
包含delete运算符的内存释放函数一定不要抛出异常。swap函数一定不要抛出异常。大多数析构函数默认情况下
Enforcement(实施建议)
Catch destructors, deallocation operations, and swaps that throw. Catch such operations that are not noexcept.
捕捉抛出异常的析构函数,内存释放操作和swap函数。捕捉这些操作中没有声明为noexcept的情况。
“C++析构函数,内存释放和swap操作分析”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注创新互联网站,小编将为大家输出更多高质量的实用文章!
分享名称:C++析构函数,内存释放和swap操作分析
当前地址:http://cdiso.cn/article/jgogoc.html