温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++析构函数,内存释放和swap操作分析

发布时间:2021-11-24 16:37:54 来源:亿速云 阅读:209 作者:iii 栏目:大数据

本篇内容介绍了“C++析构函数,内存释放和swap操作分析”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

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操作分析”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI