我试图更深入地了解编程语言的底层操作是如何工作的,尤其是它们是如何与操作系统/CPU 交互的。我可能已经阅读了 Stack Overflow 上每一个与堆栈/堆相关的线程中的每一个答案,它们都非常棒。但还有一件事我没有完全理解。
请考虑伪代码中的这个函数,它往往是有效的 Rust 代码; -)
fn foo() {
let a = 1;
let b = 2;
let c = 3;
let d = 4;
// line X
doSomething(a, b);
doAnotherThing(c, d);
}
下面是我假设堆栈在 X 行的样子:
Stack
a +-------------+
| 1 |
b +-------------+
| 2 |
c +-------------+
| 3 |
d +-------------+
| 4 |
+-------------+
现在,我读到的关于堆栈如何工作的所有内容都是它严格遵守 LIFO 规则(后进先出)。就像堆栈数据类型一样。NET、 Java 或任何其他编程语言。
But if that's the case, then what happens after line X? Because obviously, the next thing we need is to work with a
and b
, but that would mean that the OS/CPU (?) has to pop out d
and c
first to get back to a
and b
. But then it would shoot itself in the foot, because it needs c
and d
in the next line.
因此,我想知道 没错在幕后发生了什么?
另一个相关的问题,假设我们传递一个引用到另一个函数,如下所示:
fn foo() {
let a = 1;
let b = 2;
let c = 3;
let d = 4;
// line X
doSomething(&a, &b);
doAnotherThing(c, d);
}
从我的理解来看,这意味着 doSomething
中的参数基本上指向相同的内存地址,如 foo
中的 a
和 b
。但是这又意味着没有 弹出堆栈,直到我们到达 ABC1和 b
发生。
Those two cases make me think that I haven't fully grasped how 没错 the stack works and how it strictly follows the LIFO rules.