C++ 是否限制递归深度?

Does C++ limit recursion depth?(C++ 是否限制递归深度?)
本文介绍了C++ 是否限制递归深度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在 Python 中存在最大递归深度.似乎是因为 Python 被解释而不是编译.C++ 有相同的概念吗?还是只连接内存限制?

In Python there is a maximum recursion depth. Seems it is because Python is interpreted rather than compiled. Does C++ have the same concept? Or it is connected only with RAM limit?

推荐答案

C++ 中的限制是由于堆栈的最大大小.这通常比 RAM 的大小小几个数量级,但仍然相当大.(幸运的是,像字符串内容这样的大东西通常不会保存在堆栈本身中.)

The limit in C++ is due to the maximum size of the stack. That's typically less than the size of RAM by quite a few orders of magnitude, but is still pretty large. (Luckily, large things like string contents are typically held not on the stack itself.)

堆栈限制通常可在操作系统级别进行调整.(如果您使用的是 Unix,请参阅内置 ulimit shell 的文档.)这台机器 (OSX) 上的默认值为 8 MB.

The stack limit is typically tunable at the OS level. (See the docs for the ulimit shell built-in if you're on Unix.) The default on this machine (OSX) is 8 MB.

当然,在计算递归深度时,堆栈的大小本身并不完全有帮助.要知道这一点,您必须计算递归函数(也称为堆栈帧)的激活记录(或多个记录)的大小.最简单的方法(我知道)是使用反汇编器(大多数调试器的功能)并在每个函数的开始和结束时读出堆栈指针调整的大小.这是乱七八糟的.(您可以通过其他方式解决这个问题——例如,计算两次调用中指向变量的指针之间的差异——但它们甚至更令人讨厌,尤其是对于可移植代码.从反汇编中读取值更容易 IMO.)

Of course, the size of the stack doesn't entirely help by itself when it comes to working out how deep you can recurse. To know that, you have to compute the size of the activation record (or records) of the recursive function (also called a stack frame). The easiest way to do that (that I know of) is to use a disassembler (a feature of most debuggers) and to read out the size of the stack pointer adjustments at the start and end of every function. Which is messy. (You can work it out other ways –for example, computing the difference between pointers to variables in two calls – but they're even nastier, especially for portable code. Reading the values out of the disassembly is easier IMO.)

这篇关于C++ 是否限制递归深度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do compilers treat variable length arrays(编译器如何处理变长数组)
Deduce template argument from std::function call signature(从 std::function 调用签名推导出模板参数)
check if member exists using enable_if(使用 enable_if 检查成员是否存在)
Standard Library Containers with additional optional template parameters?(具有附加可选模板参数的标准库容器?)
Uses of a C++ Arithmetic Promotion Header(C++ 算术提升标头的使用)
Parameter pack must be at the end of the parameter list... When and why?(参数包必须位于参数列表的末尾...何时以及为什么?)