c++引用函数内部的函数

c++ reference function inside function

本文关键字:函数 内部 c++ 引用      更新时间:2023-10-16

下面是我的场景的简化示例(看起来很常见);

#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。