函数的变量存储在哪里?在堆栈还是堆上? [英] Where variables of a function is store? on stack or heap?

查看:731
本文介绍了函数的变量存储在哪里?在堆栈还是堆上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当程序调用一个函数时,为该函数中的变量分配哪种类型的数据结构的内存?堆还是堆?为什么?

When a program calls a function, in which type of data structure is memory allocated for the variables in that function? Heap or stack? why?

在我看来,它应该存储在堆栈中,因为它们不一定是引用类型.但是,在我阅读答案的地方,有人说它们存储在堆上,并且在函数返回值后释放.

In my opinion it should store on stack because they are not necessarily reference types. But Where I read the answer, it is stated that they store on heap and free after function returns a value.

推荐答案

要复杂得多,而且使用堆栈和堆的事实实际上是实现细节.谈论数据的生命周期更有意义.短期数据将存储在堆栈中(或寄存器中).寿命长的数据存储在堆中.

It is a little more complicated than that and the fact that the stack and heap are used are really implementation details. It makes more sense to talk about lifetime of data. Short lived data will be stored on the stack (or in registers). Long lived data is stored on the heap.

引用类型的实例始终被认为是长期存在的,因此它们会进入堆中.值类型可以是两种.局部值类型通常存储在堆栈上,但是如果某些因素将此类变量的寿命延长到函数范围之外,则将其存储在堆栈上就没有意义.捕获的变量会发生这种情况,即使它们是值类型,它们也将存储在堆中.

Instances of reference types are always considered long lived, so they go on the heap. Value types can be both. Local value types are typically stored on the stack, but if something extends the lifetime of such a variable beyond the scope of the function, storing it on the stack wouldn't make sense. This happens for captured variables and these will be stored on the heap even if they are value types.

这篇关于函数的变量存储在哪里?在堆栈还是堆上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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