gpt4 book ai didi

c++ - 如何正确实现最终条件?

转载 作者:太空宇宙 更新时间:2023-11-04 15:10:14 25 4
gpt4 key购买 nike

这就是我想要做的(这是对真实项目的简化):

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..";
}
}

我无法改变 process() 的工作方式,因为这个函数不是在项目中创建的,而是一个第三方函数。它与全局变量 paramresult 一起工作,我们无法更改它。

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..";
}
}

最佳答案

“finally”之类的情况在 C++ 中使用保护对象处理,它们在析构函数中完成它们的 finally 事情。恕我直言,这是更强大的方法,因为您必须分析要最终确定的情况,以便创建可重用的对象。在这种情况下,我们需要让进程租用,因为参数和返回是在全局变量中传递的。解决方案是在进入时保存它们的值并在退出时恢复它们:

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;
}
}

关于c++ - 如何正确实现最终条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3263135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com