这就是我想要做的(这是一个真实项目的简化):
int param;
int result;
void isolated(int p) {
param = p;
try {
// make calculations with "param" and place the
// result into "result"
process();
} catch (...) {
throw "problems..";
}
}
Run Code Online (Sandbox Code Playgroud)
我无法改变process()工作方式,因为该功能不是在项目中创建的,而是第三方功能.它适用于全局变量param,result我们无法改变它.
使用其他参数isolated()回调时出现问题process().我想抓住这种情况,但不知道该怎么做,因为finally在C++中不存在.我觉得我应该使用RAII技术,但在这种情况下无法弄清楚如何正确使用它.
这就是我如何使用代码重复:
int param;
int result;
void isolated(int p) {
static bool running;
if (running) {
throw "you can't call isolated() from itself!";
}
running = true;
param = p;
try {
// make calculations with "param" and place the
// result into "result"
process();
running = false;
} catch (...) {
running = false; // duplication!
throw "problems..";
}
}
Run Code Online (Sandbox Code Playgroud)
"最后"就像在C++中使用保护对象处理情况一样,它们最终在析构函数中执行.这是IMHO更强大的方法,因为您必须分析情况以最终确定以创建可重用的对象.在这种情况下,我们需要使进程租用,因为参数和返回在全局变量中传递.解决方案是在输入时保存它们的值并在退出时恢复它们:
template<class T>
class restorer
{
T &var; // this is the variable we want to save/restore
T old_value; // the old value
restorer(const restorer&);
void operator=(const restorer&);
public:
restorer(T &v) : var(v), old_value(v) {}
~restorer() { var=old_value; }
};
int param;
int result;
int isolated(int p) {
restorer<int> rest_param(param);
restorer<int> rest_result(result);
param = p;
try {
// make calculations with "param" and place the
// result into "result"
process();
return result;
} catch (...) {
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)