让我们说当我抛出异常时,我会做一些需要清理的事情。
例如,假设我正在创建一个动态数组,我需要构造对象,但是它们的构造函数可能会抛出异常:
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
(注意:此示例仅意味着显示两种技术之间的区别。我知道它不是完美的代码,所以请做不 专注于这个特定的例子。它只是为了说明。)
答案 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