为什么要在堆上而不是堆栈上分配内存? [英] Why would you ever want to allocate memory on the heap rather than the stack?

查看:37
本文介绍了为什么要在堆上而不是堆栈上分配内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
什么时候最好使用堆栈而不是堆,反之亦然?

我已经阅读了一些关于堆与堆栈的其他问题,但他们似乎更关注堆/堆栈的作用,而不是您为什么要使用它们.

I've read a few of the other questions regarding the heap vs stack, but they seem to focus more on what the heap/stack do rather than why you would use them.

在我看来,堆栈分配几乎总是首选,因为它更快(只是移动堆栈指针而不是在堆中寻找可用空间),并且您不必手动释放分配的内存完成使用它.我可以看到使用堆分配的唯一原因是,如果您想在函数中创建一个对象,然后在该函数范围之外使用它,因为从函数返回后堆栈分配的内存会自动取消分配.

It seems to me that stack allocation would almost always be preferred since it is quicker (just moving the stack pointer vs looking for free space in the heap), and you don't have to manually free allocated memory when you're done using it. The only reason I can see for using heap allocation is if you wanted to create an object in a function and then use it outside that functions scope, since stack allocated memory is automatically unallocated after returning from the function.

是否还有其他我不知道的使用堆分配而不是堆栈分配的原因?

Are there other reasons for using heap allocation instead of stack allocation that I am not aware of?

推荐答案

有几个原因:

  • 主要的一点是,通过堆分配,您可以最灵活地控制对象的生命周期(从 malloc/callocfree);
  • 堆栈空间通常是比堆空间更有限的资源,至少在默认配置中是这样;
  • 分配堆空间失败可以正常处理,而堆栈空间用完通常无法恢复.

如果没有灵活的对象生命周期,几乎不可能编写有用的数据结构,例如二叉树和链表.

Without the flexible object lifetime, useful data structures such as binary trees and linked lists would be virtually impossible to write.

这篇关于为什么要在堆上而不是堆栈上分配内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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