GC中的栈(stack)、堆(heap)、 静态区(static) 的区别

来源:互联网 发布:如何安装管家婆软件 编辑:程序博客网 时间:2024/06/01 09:17


本文转自:http://blog.sina.com.cn/s/blog_4d52f5a701008opc.html


栈区(stack)— 由编译器自动分配释放 ,存放函数的参数值,局部变量的值等。

堆区(heap) 一般由程序员分配释放, 若程序员不释放,程序结束时可能由OS回收 

静态区(static)—,全局变量和静态变量的存储是放在一块的,初始化的全局变量和静态变量在一块区域, 未初始化的全局变量和未初始化的静态变量在相邻的另一块区域。


下面是引自[Think in C++]的一段原文:

The stack is an area in memory that is used directly by the microprocessor to store data during program execution.Variables on the stack are sometimes called automatic or scoped variables.

The second approach is to create objects dynamically in a pool of memory called the heap.In this approach you don’t know until runtime how many objects you need, what their lifetime is, or what their exact type is. Those decisions are made at the spur of the moment while the program is running. If you need a new object, you simply make it on the heap when you need it, using the new keyword. When you’re finished with the storage, you must release it using the delete keyword.

The static storage area is simply a fixed patch of memory that is allocated before the program begins to run. 

   
从这段话可以理解出对象在栈中(stack)和静态区(static)程序员不能使用new和Delete来对其操作.因此栈中(stack)和静态区(static)的变量是不受程序员的程序控制的,既然不是由程序控制的?那是由誰控制的?其实可以这样理解的:由编译器控制的。

而堆(heap),C++的程序员则可以通过new和delete的指令对其进行操作,因此給程序编写带来了灵活性.当然对于Java或者是C#的程序员来说,堆(heap)的控制也由不得他了,而是Java或C#内部的垃圾回收器帮程序员来打理,通常Java或者是C#的程序员只要new下就不用去delete了,这个delelte则是由内部的GC垃圾回收器去打理了。

实际上Java的底层是C++编写的,当然遵循上述规则。


0 0
原创粉丝点击