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

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

问题描述

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

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天全站免登陆