俗一把,谈谈stack和heap

thinking in c++一书中,谈到的。

 

为了最大化运行速度,the storage and lifetime can be determined while the program is being written, by placing the objects on the stack or in static storage. The stack is an area in memory that is used directly by the microprocessor to store data during program execution. Varaibles on the stack are sometimes called automatic or scoped variables. The static storage area is simply a fixed patch of memory that is allocated before the program begins to run.

 

 

Using the stack or static storage area placres a priority on the speed of storage allocation and release.

 

因此翻译过来,stack栈,这个存储空间,只要是在run前能够将存储空间和生命周期确定的量,均保存在该区内。因此,从这个意义上说,全局变量,局部变量,静态变量等均保存在栈里。

 

栈中的变量的生命周期,由编译器确定。即,全局变量或局部变量,编译器自动确定。

 

create objects dynamically in a pool of memory called the heap. In this approach you do not 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.

 

 

因此,heap堆中,动态创建的一些对象/变量,这些量的确切数量、生命周期、确切类型均可以未知,直到运行程序中。如果需要一个新的对象,则调用new关键词来生成在堆中。当你完成了该堆空间的使用,你需要用delete将其释放掉。而在堆中的变量,必须由程序员显示地调用new和delete进行声明和销毁。

 

貌似在堆中,为了不人为进行delete,可以使用垃圾收集器garbage collector,有很多操作环境允许垃圾收集器使用,但是C++中并不包含,虽然也有第三方的垃圾收集器可供C++使用。我没有用过这个东西,大概这也是很多人不喜欢C++的一个原因?毕竟如果你没有及时的有效地充分地释放一些变量,会造成内存泄露,这也是一个很BIG的problem。

 

这是我第一次感觉对stack和heap有点了解,以前看过很多人说的,总是觉得不够清晰。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值