C Sharp 中的栈和堆
谁能告诉我内存分配是如何完成的,哪个对象将存储在堆栈中,哪个对象将存储在堆部分中记忆?
Possible Duplicate:
Why are structs stored on the stack while classes get stored on the heap(.NET)?
Can anyone tell me that how the allocation of memory is done that which object is to be stored in stack and which to be in heap portion of the memory?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Microsoft 的 C# 编译器和 CLR 实现中,当值是临时值、局部变量或形式参数时,值类型存储在堆栈中,既不是匿名方法的封闭外部变量,也不是迭代器块中的值。
当然,如果不需要的话为什么要把东西存储在堆栈上呢?一些值类型的局部变量根本不会进入堆栈;它们一生都会保留在寄存器中。
值类型的其他值存储在堆上 - 装箱值类型、引用类型上的值类型字段等。
值类型当然既不能存储在堆栈中,也不能存储在寄存器中,也不能存储在托管堆中;它们可以使用不受 CLR 控制的一些完全不同的内存管理器存储在非托管内存中。
(当然请注意,在“堆栈”中使用“the”会产生微妙的误导;一个进程中可以有许多堆栈。不一定只有一个。)
所有这些都是实现细节,如有更改,恕不另行通知。
另外,显然使用堆栈分配声明分配的内容是在堆栈上分配的。
有关此主题的更多信息,请参阅我的文章:
http://blogs.msdn.com/b/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx
http ://blogs.msdn.com/b/ericlippert/archive/2009/05/04/the-stack-is-an-implementation-detail-part-two.aspx
你为什么关心?运行时会为您管理所有这些细节,因此您不必担心。您只是好奇,还是这会导致一些更大的问题?
In the Microsoft implementation of the C# compiler and CLR, value types are stored on the stack when the value is a temporary value, local variable or formal parameter, that is neither a closed-over outer variable of an anonymous method nor in an iterator block.
Of course, why store stuff on the stack if you don't need to? Some local variables of value type never get on the stack at all; they stay in registers for their entire lifetimes.
Other values of value types are stored on the heap - boxed value types, value-typed fields on a reference type, and so on.
Value types can of course be stored on neither the stack, nor registers, nor the managed heap; they could be stored in unmanaged memory using some completely other memory manager not under control of the CLR.
(And of course note that using "the" in "the stack" is subtly misleading; there can be many stacks in a process. There need not be just one.)
All this is an implementation detail and subject to change without notice.
Also, obviously stuff allocated with the stack alloc declaration is allocated on the stack.
For more information on this topic see my articles on it:
http://blogs.msdn.com/b/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx
http://blogs.msdn.com/b/ericlippert/archive/2009/05/04/the-stack-is-an-implementation-detail-part-two.aspx
Why do you care? The runtime manages all these details for you so that you don't have to worry about it. Are you just curious, or is this leading to some larger question?
3 个经验法则:
3 rules of thumb: