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

时间:2022-07-22
本文章向大家介绍C++核心准则E.13: 直接拥有一个对象所有权时永远不要抛出异常,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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