虚值期权到期怎样行权(C核心准则E.13:直接拥有一个对象所有权时永远不要抛出异常)
虚值期权到期怎样行权(C核心准则E.13:直接拥有一个对象所有权时永远不要抛出异常)void no_leak_simplified(int x) { vector<int> v(7); // ... }Note(注意)另外一个解决方案(通常更好)是用局部变量来避免使用指针。void leak(int x) // don't: may leak { auto p = new int{7}; if (x < 0) throw Get_me_out_of_here{}; // may leak *p // ... delete p; // we may never get here }One way of avoiding such problems is to use resource handles consistently:避免这种问题的一种方法是始终如一地使用资源句柄。void no_leak(int x) {
Reason(原因)
That would be a leak.
那样做会发生泄露。
Example(示例)
void leak(int x) // don't: may leak
{
auto p = new int{7};
if (x < 0) throw Get_me_out_of_here{}; // may leak *p
// ...
delete p; // we may never get here
}
One way of avoiding such problems is to use resource handles consistently:
避免这种问题的一种方法是始终如一地使用资源句柄。
void no_leak(int x)
{
auto p = make_unique<int>(7);
if (x < 0) throw Get_me_out_of_here{}; // will delete *p if necessary
// ...
// no need for delete p
}
Another solution (often better) would be to use a local variable to eliminate explicit use of pointers:
另外一个解决方案(通常更好)是用局部变量来避免使用指针。
void no_leak_simplified(int x)
{
vector<int> v(7);
// ...
}
Note(注意)
If you have local "things" that requires cleanup but is not represented by an object with a destructor such cleanup must also be done before a throw. Sometimes finally() can make such unsystematic cleanup a bit more manageable.
如果局部的“某物”需要清除,但却没有实现为一个具有析构函数的对象,这些清理操作也必须在抛出异常之前进行。有时,finally函数可以让这种非系统化的清理动作稍微容易管理一些。
原文链接
https://github.com/isocpp/CppCoreGUIdelines/blob/master/CppCoreGuidelines.md#e13-never-throw-while-being-the-direct-owner-of-an-object
新书介绍
以下是本人3月份出版的新书,拜托多多关注!
本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。
对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。
觉得本文有帮助?请分享给更多人。
关注微信公众号【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!