我正在学习 C++,目前我正在摆弄以下代码:
class Bar;
struct Callback {
virtual void Continue(Bar&) = 0;
};
// ...
void Foo(Bar& _x, Callback& result)
{
// Do stuff with _x
if(/* some condition */) {
// TODO: Force unwind of stack
result.Continue(_x);
return;
}
// Do more stuff with _x
if(/* some other condition */) {
// TODO: Force unwind of stack
result.Continue(_x);
return;
}
// TODO: Force unwind of stack
Bar y; // allocate something on the stack
result.Continue(y);
}
主要思想是我知道在每个站点result.Continue被调用时,该函数Foo也会返回。因此,堆栈可以在调用延续之前展开。
由于用户代码将以递归方式使用它,我担心此代码可能会导致堆栈溢出。据我了解,参数_x和在执行result时保留在堆栈result.Continue中,因为堆栈仅在Foo返回时才展开。
编辑:该Continue函数可能(并且可能会)调用该Foo方法:导致递归。简单的尾调用优化Continue并不会Foo导致堆栈溢出。
在返回之前,我能做些什么来强制展开堆栈,Foo保留result一个临时(register?)变量,然后执行该继续?