什么时候应该在堆上分配? (C ++) [英] When should I allocate on the heap? (C++)

查看:120
本文介绍了什么时候应该在堆上分配? (C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的不明白什么时候应该分配内存在堆上,当我应该在堆栈上分配。我真正知道的是,在堆栈上的分配更快,但由于堆栈更小,我不应该使用它来分配大型数据结构;在决定在哪里分配内存时,我应该考虑什么其他事情?编辑:我应该在哪里分配实例变量?

I don't really understand when I should be allocating memory on the heap and when I should allocate on the stack. All I really know is that allocating on the stack is faster, but since the stack is smaller I shouldn't use it to allocate large data structures; what other things should I take into account when deciding where to allocate memory? where should I allocate instance variables?

推荐答案


  1. Lifetime == scope。

  2. 如果您需要手动控制对象的生命周期,请将其分配到堆上。

  3. 如果对象很大,并且堆栈不够大,则将其分配给堆。

  4. 使用在情况2和3中,它允许你在堆栈上使用对象来处理可能是你的对象的资源 - 一个很好的例子是std :: shared_ptr / boost :: shared_ptr。

  1. Allocate on the stack for most objects. Lifetime == scope.
  2. If you need to control manually the lifetime of the object, allocate it on the heap.
  3. If the object is big and the stack is not big enough for it, allocate it on the heap.
  4. Use the (badly names) RAII idiom in cases 2 and 3, it allow you to use object on the stack that manipulate resources that might be your objects on the heap -- a good example are the smart pointers like std::shared_ptr/boost::shared_ptr.

这篇关于什么时候应该在堆上分配? (C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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