問題描述
在 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++ 是否限制遞歸深度?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!