退出方法时堆栈会发生什么? [英] What happens to the stack when exiting a method?

查看:25
本文介绍了退出方法时堆栈会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 堆栈和堆是什么以及在哪里?.我有点模糊的一件事是方法退出后堆栈会发生什么.以这张图片为例:

I was reading What and where are the stack and heap?. One thing I am a bit fuzzy on is what happens to the stack after a method exits. Take this image for example:

退出方法时堆栈被清除,但这意味着什么?堆栈上的指针是否刚刚移回堆栈的开头使其为空?我希望这不是一个太宽泛的问题.当堆栈从退出方法中清除时,我不确定幕后发生了什么.

The stack is cleared upon exiting the method, but what does that mean? Is the pointer at the stack just moved back to the start of the stack making it empty? I hope this is not too broad of a question. I am not really sure what is going on behind the scenes when the stack is cleared from exiting a method.

推荐答案

调用方法时,局部变量位于栈上.对象引用也存放在栈中,对应的对象存放在堆中.

When a method is called, local variables are located on the stack. Object references are also stored on the stack, corresponding objects are store in the heap.

堆栈只是一个内存区域,它有一个开始和结束地址.JVM(java虚拟机)有一个寄存器指向当前栈顶(栈指针).如果调用了新方法,则会在寄存器中添加一个偏移量以获取堆栈上的新空间.

The stack is just a region of memory, it has a start and end address. The JVM (java virtual machine) has a register which points to the current top of the stack (stack pointer). If a new method is called, an offset will be added to the register to get new space on the stack.

当一个方法调用结束时,堆栈指针会减少这个偏移量,这释放了分配的空间.

When a method call is over, the stack pointer will be decreased by this offset, this frees the allocated space.

局部变量和其他东西(如返回地址、参数...)可能仍在堆栈中,将被下一个方法调用覆盖.

Local variables and other stuff (like return address, parameters...) may still on the stack and will be overwritten by next method call.

顺便说一句:这就是 java 将所有对象存储在堆中的原因.当一个对象位于堆栈上,并且您将返回指向堆栈的引用时,该对象可能会被下一个方法调用销毁.

BTW: this is why java stored all objects in heap. When an object would be located on the stack, and you would return the reference which points to the stack, the object could be destroyed by next method call.

这篇关于退出方法时堆栈会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆