c++引用函数内部的函数
c++ reference function inside function
下面是我的场景的简化示例(看起来很常见);
#include <signal.h>
void doMath(int &x, int &y);
void signal_handler(int signal);
int main() {
signal (SIGINT,signal_handler);
int x = 10;
int y;
doMath(x,y);
while(1);
return 0;
}
void doMath(int &x, int &y) {
for(int y=0; y<=x; y++) {
cout << y << endl;
}
return;
}
void signalHandler(int signal){
doMath(x,y);
exit(1);
}
这个基本程序在屏幕上打印1到10,并一直挂在那里,直到按下CTRL+C。此时,我希望doMath()函数再次运行。我能看到这种情况发生的唯一方法是,如果我将x和y传递给signalhandler(),这样它就可以将它们传递给doMath(),并引用doMath函数。
在我的实际程序中,有两个doMath()函数和更多的变量,我希望最终转储变量值。因此,将所有这些变量传递给signalHandler,然后再传递给这两个函数,这似乎是一种效率低下的方式。还有别的办法吗?
我认为您需要使用一个全局变量。
虽然一般情况下应避免使用全局变量,但有时别无选择。尽量少用,并清楚地记录它们的使用情况:
#include <signal.h>
void signalHandler(int signal);
void doMath(int &x, int &y);
struct DoMathArgs {
int x;
int y;
void callDoMath() { doMath(x,y); }
};
// We have to use this global variable to pass the arguments to doMath when
// the signal is caught, since the signal handler isn't passed any arguments
// that we can use for our own data.
DoMathArgs global_do_math_args;
int main() {
signal (SIGINT,signalHandler);
global_do_math_args.x = 10;
global_do_math_args.callDoMath();
doSomethingForever();
return 0;
}
void signalHandler(int signal) {
global_do_math_args.callDoMath();
exit(1);
}
void doMath(int &x, int &y) {
for(int y=0; y<=x; y++) {
cout << y << endl;
}
return;
}
一种更有效的方法是定义一个事件,在main中等待它,在信号中设置它,等待后再次在main中调用doMath。
相关文章:
- 在函数内部的声明中初始化数组,并在外部使用它
- 使用C链接在函数内部创建C++模板
- 指针没有更新它在void函数内部指向的值
- SDL_PollEvent() 无法捕获类函数内部SDL_QUIT?
- 为什么从另一个构造函数内部调用C++构造函数不修改类变量?
- WriteProcessMemory 在函数内部失败
- 如何在C++中传递lambda函数内部的对象实例
- 在析构函数内部处理异常(但不抛出)
- 在函数内部传递字符 *str
- 仅在函数内部构建对象时EXC_BAD_ACCESS
- 是否可以使用类的析构函数内部函数来重置值?
- 如何在函数内部使用 zmq(以非阻塞方式)在客户端请求时获取函数的状态?
- 在函数内部错误定位后,从函数中释放返回的指针会导致芯片崩溃
- 我如何从循环内部使用迭代器的函数内部的getter中检索特定的成员
- C++ 修改函数内部的字符
- 从对象成员函数内部删除操作的技术 /设计模式
- C++14 使用捕获说明符递增 lambda 函数内部的值
- 在成员函数内部调用成员函数
- 如何在类构造函数内部对同一类的成员函数启动pthread
- Arduino C++:F()宏在函数内部有意义吗