在c++中,有没有一种方法可以从一个函数跳到另一个函数

In c++, is there a way to jump from one function to another

本文关键字:函数 另一个 一个 一种 c++ 有没有 方法      更新时间:2023-10-16

在C++中,如果调用堆栈中没有A(),我能从A()内部跳到B()吗?这个案子有类似goto的东西吗?我的情况是,我应该在一个物体的功能结束时摧毁它。

class timeBomb{
public:
  void detonate(int time){
    sleep(time);
    goto this->blast(this); //something like that
  };
  timeBomb();
  static void blast(timeBomb bomb){
    delete bomb;
  }
}
int main(){
  timeBomb *myBomb = new timeBomb();
  myBomb->detonate(2);
  return 0;
}

我本可以带着delete this;离开的。但在我的代码中,在特定条件下,构造函数本身必须调用一个函数,而这个函数又调用一个类似于引爆的函数。

为了解决我的问题,我本可以问我是否可以中止创建一个对象。但我发现在调用堆栈中从一个函数跳到另一个避免父函数既有趣又有用。

您可以"回到"以前使用setjmplongjmp的地方,但在代码中没有任何东西可以跳到随机的新位置(除了各种与系统相关的东西,比如使用内联汇编程序或类似的东西,这仍然很难变得非常通用,因为您需要注意堆栈清理和其他类似的事情)。

如果您有通用功能,那么创建一个(private)方法,并从所有需要该功能的方法中调用它:

class timeBomb {
public:
  void detonate(int time){
    sleep(time);
    blast();
  };
  timeBomb();
private:
  void blast(){
    delete this;   // Very dangerous!
  }
};