避免“如果清除失败”的模式重复 [英] Pattern to avoid "if failed cleanup" repetition
问题描述
我有一些看起来像这样的代码:
I have some code that looks like this:
int myfunc()
{
blah a;
blah2 b;
blah3 c;
blah4 d;
blah5 e;
int iRes = DoSomething1(a, b, c);
if (iRes > 0)
{
clean1(a, b, c);
clean2(d, e);
log_error();
return 1;
}
iRes = DoSomething2(a, c, e);
if (iRes > 0)
{
clean1(a, b, c);
clean2(d, e);
log_error();
return 1;
}
...
iRes = DoSomething10(c, d, e);
if (iRes > 0)
{
clean1(a, b, c);
clean2(d, e);
log_error();
return 1;
}
clean1(a, b, c);
clean2(d, e);
return 0;
}
如何在C或C ++中避免重复 if(iRes> 0){clean1(a,b,c); clean2(d,e); log_error();返回1; }
在每个函数调用之后?
How, in C or C++, avoid the repetition of if (iRes > 0) { clean1(a, b, c); clean2(d, e); log_error(); return 1; }
after each function calls?
注意:
- 在实际代码中,这些函数
DoSomethingx()
和cleanx()
是API函数,不是我自己写的 - 我想避免使用第二个函数
clean ()
在myfunct()
之外定义,它将处理清理和错误 - 我考虑过使用预处理程序宏,但我怀疑在这种情况下这是否是一个好习惯
- In the real code, these functions
DoSomethingx()
andcleanx()
are API functions, not written by myself - I'd like to avoid having a second function
clean()
defined outside ofmyfunct()
that would handle the cleanup + error - I thought about using preprocessor macro, but I doubt it's a good practice for such situations
示例:
此代码是这种情况的一个示例:实际上,每10行代码= 仅2行仅用于实际执行某操作 + 8行错误测试和清除...更好吗?
This code is an example of such a situation: every 10 lines of code is in fact = 2 lines only for actually doing something + 8 lines of error testing and cleanup... Can we do nicer?
推荐答案
正如贾斯汀(Justin)所言,答案会有所不同
As Justin mentioned, the answers will be quite different depending on the language.
如果您在C语言中,这是 goto
拥有据点的最终位置之一语言。例如,如果您有:
If you are in C, this is one of the final places where goto
has a stronghold in the language. For example, if you have:
int myfunc()
{
blah a;
blah2 b;
blah3 c;
blah4 d;
blah5 e;
int iRes = DoSomething1(a, b, c);
if (iRes > 0)
{
goto error_cleanup;
}
iRes = DoSomething2(a, c, e);
if (iRes > 0)
{
goto error_cleanup;
}
/*...*/
iRes = DoSomething10(c, d, e);
if (iRes > 0)
{
goto error_cleanup;
}
/* SUCCESS */
clean1(a, b, c);
clean2(d, e);
return 0;
/* ERROR EXIT POINT */
error_cleanup:
clean1(a, b, c);
clean2(d, e);
log_error();
return 1;
}
但是,在C ++中,即使出现异常,我们也需要处理此清理代码抛出,这又使事情变得更加棘手。但是,在c ++中,我们也有RAII,这意味着应该使用析构函数。
However, in C++ we need to deal with this cleanup code even when exceptions are thrown, which puts another wrench into the scheme of things. However, in c++ we also have RAII, which means destructors is the way to go.
这篇关于避免“如果清除失败”的模式重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!