是否可以在递归 C++ 函数中捕获 堆栈溢出异常
?如果是,怎么办?
那么在这种情况下会发生什么
void doWork()
{
try() {
doWork();
}
catch( ... ) {
doWork();
}
}
我不是在寻找特定操作系统的答案。一般情况下
最佳答案
这本身并不是一个异常(exception),但如果您只是想将堆栈使用量限制在固定数量,您可以这样做:
#include <stdio.h>
// These will be set at the top of main()
static char * _topOfStack;
static int _maxAllowedStackUsage;
int GetCurrentStackSize()
{
char localVar;
int curStackSize = (&localVar)-_topOfStack;
if (curStackSize < 0) curStackSize = -curStackSize; // in case the stack is growing down
return curStackSize;
}
void MyRecursiveFunction()
{
int curStackSize = GetCurrentStackSize();
printf("MyRecursiveFunction: curStackSize=%i\n", curStackSize);
if (curStackSize < _maxAllowedStackUsage) MyRecursiveFunction();
else
{
printf(" Can't recurse any more, the stack is too big!\n");
}
}
int main(int, char **)
{
char topOfStack;
_topOfStack = &topOfStack;
_maxAllowedStackUsage = 4096; // or whatever amount you feel comfortable allowing
MyRecursiveFunction();
return 0;
}
关于c++ - 在递归 C++ 函数中捕获 "Stack Overflow"异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1578878/