前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则E.13: 直接拥有一个对象所有权时永远不要抛出异常

C++核心准则E.13: 直接拥有一个对象所有权时永远不要抛出异常

作者头像
面向对象思考
发布2020-08-04 17:09:00
3160
发布2020-08-04 17:09:00
举报

E.13: Never throw while being the direct owner of an object

E.13: 直接拥有一个对象所有权时永远不要抛出异常

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

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • E.13: 直接拥有一个对象所有权时永远不要抛出异常
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档