使用析构函数与catch(...)进行失败处理(...){fix();扔; }

时间:2014-03-12 09:29:20

标签: c++ exception-handling try-catch exception-safety

让我们说当我抛出异常时,我会做一些需要清理的事情。

例如,假设我正在创建一个动态数组,我需要构造对象,但是它们的构造函数可能会抛出异常:

size_t const n = 100;
T *const p = static_cast<T *>(operator new(sizeof(T) * n));
size_t i;
for (i = 0; i < n; ++i)
    new (&p[i]) T(1, 2, 3);      // Not exception-safe if T::T(T const &) throws!

我可以通过 catch (...) { ...; throw; }

修复它
size_t const n = 100;
T *const p = static_cast<T *>(operator new(sizeof(T) * n));
size_t i;
try
{
    for (i = 0; i < n; ++i)
        new (&p[i]) T(1, 2, 3);
}
catch (...)
{
    while (i > 0)
        p[--i].~T();
    operator delete(p);
    throw;
}

或通过作用域的析构函数

size_t n = 100;
struct Guard
{
    T *p;
    size_t i;
    Guard(size_t n) : i(), p(static_cast<T *>(operator new(sizeof(T) * n))) { }
    ~Guard()
    {
        while (i > 0)
            p[--i].~T();
        operator delete(p);
    }
} guard(n);

for (guard.i = 0; guard.i < n; ++guard.i)
    new (&guard.p[guard.i]) T(1, 2, 3);

guard.i = 0;     // Successful... "commit" the changes
guard.p = NULL;  // or whatever is necessary to commit the changes

我应该选择使用哪种技术?为什么?

注意:此示例意味着显示两种技术之间的区别。我知道它不是完美的代码,所以请 专注于这个特定的例子。它只是为了说明。)

2 个答案:

答案 0 :(得分:2)

析构函数的解决方案优于显式try/catch

  • 它是可重用的,如果你需要在另一个函数中进行类似的初始化,你可以重用相同的防护类
  • 它更容易维护 - 让我们说在某些情况下你的函数需要返回失败但没有抛出异常。有了防护等级,它或多或少会自动处理
  • 它更干净,因为代码更模块化

答案 1 :(得分:2)

一般来说,我会说这是扩展安全的问题。

try/catch的问题有两方面:

  • 安全问题:忽略catch(某种程度上)无法清理的任何早期返回
  • 缩放问题:嵌套try/catch块会使代码混乱
  • 范围问题:要在catch中访问,必须在try之前定义变量,从而支持default-construction / nullability;这可能很痛苦

相反,Deferred Statements和Guards不会创建不必要的块/范围,因此不会缩进,并且线性读取。

示例:

char buffer1[sizeof(T)];
try {
    new (buffer1) T(original);

    char buffer2[sizeof(T)];
    try {
        new (buffer2) T(original);

        // stuff here

    } catch(...) {
        reinterpret_cast<T*>(buffer2)->~T();
        throw;
    }

} catch(...) {
    reinterpret_cast<T*>(buffer1)->~T();
    throw;
}

与:相比:

char buffer1[sizeof(T)];
new (buffer1) T(original);
Defer const defer1{[&buffer1]() { reinterpret_cast<T*>(buffer1)->~T(); } };

char buffer2[sizeof(T)];
new (buffer2) T(original);
Defer const defer1{[&buffer2]() { reinterpret_cast<T*>(buffer2)->~T(); } };

// stuff here

我会注意到概括这些似乎是个好主意:

class Guard {
public:
    explicit Guard(std::function<void()> f): _function(std::move(f)) {}

    Guard(Guard&&) = delete;
    Guard& operator=(Guard&&) = delete;

    Guard(Guard const&) = delete;
    Guard& operator=(Guard const&) = delete;

    ~Guard() {
        if (not _function) { return; }
        try { _function(); } catch(...) {}
    }

    void cancel() { _function = std::function<void()>{}; }

private:
    std::function<void()> _function;
}; // class Guard

class Defer {
public:
    explicit Defer(std::function<void()> f): _guard(std::move(f)) {}
private:
    Guard _guard;
}; // class Defer