Gee*_*eho 3 c++ exception-handling exception
当我有一个方法调用一组提供强有力保证的方法时,我经常遇到回滚更改的问题,以便也有一个强大的保证方法.我们来举个例子:
// Would like this to offer strong guarantee
void MacroMethod() throw(...)
{
int i = 0;
try
{
for(i = 0; i < 100; ++i)
SetMethod(i); // this might throw
}
catch(const std::exception& _e)
{
// Undo changes that were done
for(int j = i; j >= 0; --j)
UnsetMethod(j); // this might throw
throw;
}
}
// Offers strong guarantee
void SetMethod(int i) throw(...)
{
// Does a change on member i
}
// Offers strong guarantee
void UnsetMethod() throw(...)
{
// Undoes a change on member i
}
Run Code Online (Sandbox Code Playgroud)
显然,UnsetMethod可能会抛出.在这种情况下,我的MacroMathod()仅提供基本保证.然而,我尽我所能提供强有力的保证,但我不能绝对确定我的UnsetMethod()不会抛出.这是我的问题:
谢谢!
尝试实现此目的的一个好方法是使您的方法适用于要修改的对象的副本.完成所有修改后,您可以交换对象(应保证交换不要抛出).这只有在有效实现复制和交换时才有意义.
此方法的优点是您try...catch
的代码中不需要任何-blocks,也没有清理代码.如果抛出异常,则在堆栈展开期间会丢弃修改后的副本,并且根本不会修改原始副本.