在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;
。但在我的代码中,在特定条件下,构造函数本身必须调用一个函数,该函数又调用像引爆这样的函数。
解决我的问题我可以问我可以中止创建一个对象。但我发现从一个函数跳转到另一个函数,避免调用栈中的父函数引人入胜且有用。
答案 0 :(得分:1)
您可以“回到过去”之前使用setjmp
和longjmp
的地方,但没有什么可以跳转到代码中的随机新位置(除了各种系统相关的东西,比如使用内联汇编程序或者其他一些东西 - 这仍然很难非常通用,因为你需要关心堆栈清理和其他类似的东西)。
答案 1 :(得分:1)
如果您有共同的功能,那么创建一个(private
)方法并从需要该功能的所有方法中调用它:
class timeBomb {
public:
void detonate(int time){
sleep(time);
blast();
};
timeBomb();
private:
void blast(){
delete this; // Very dangerous!
}
};