什么时候应该在堆栈上而不是堆上分配类 [英] When should a class be allocated on the stack instead of the heap

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

问题描述

过去,每当我需要创建一个类的实例时,我都会使用new在堆上分配它(stl类以及vec3和mat4等数学类除外).

In the past whenever I needed to create an instance of a class I would use new to allocate it on the heap (except for stl classes, and math classes like vec3 and mat4).

但是,我只是认真地查看了一些代码,并意识到从技术上讲,我可以只在堆栈上创建这些类.它们不是很大,不需要在其当前作用域之外进行修改,等等.当我(偶尔)需要将它们传递给另一个函数时,我可以像传递指针一样轻松地使用引用.

However, I was just looking critically at some of my code and realized that technically I could just be making these classes on the stack instead. They're not very big, don't need to be modified outside of their current scope, etc. When I (occasionally) need to pass them to another function I can use a reference as easily as I could pass a pointer.

过去,我总是默认在堆上分配内存,只在某些情况下才使用堆栈,但是现在我想知道默认情况下在堆栈上分配内存是否更好?

In the past I always defaulted to allocating on the heap, and only used the stack in certain cases, however now I'm wondering if it would have been better to default to allocating on the stack, and only use the heap when

  • 确实需要一个指针(即对象的生存期要超出声明的范围)
  • 类或数组对于堆栈而言太大
  • 继承需要它(抽象基类/接口)
  • 还有别的吗?

还有哪些人提出了一个问题:一个类太大(大约)太大而不能合理地分配到堆栈上?(假设我们至少在智能手机上工作,并且要升级到高端台式机)我是否只是在担心不必要的堆栈大小限制?(可能是,只要我们不谈论大型数组,并且没有一个类甚至会接近千字节)

Which also raises the question: how big a class is too big (roughly) to reasonably allocate on the stack? (assuming we're working on, at minimum, smartphones, and going up to high end desktops) Am I just worrying unnecessarily about stack size constraints? (probably, as long as we're not talking large arrays, and no class is going to be even close to a kilobyte)

推荐答案

由于两个原因,我更喜欢在堆栈上进行分配.首先,在所有其他条件相同的情况下,它比堆快.另外,取消分配是自动发生的,我不需要记住要删除它(当然,有 auto_ptr s可以帮助您解决此问题).

I prefer to allocate on the stack, for two reasons. First, all else being equal, it is faster than heap. Also, the deallocation happens automatically, I don't need to rememeber to delete it (of course, there are auto_ptrs and such to help with that).

确实需要一个指针

a pointer is really needed

可以将指针传递到堆栈上的对象.只需确保该指针的用户在其生存期到期后就不会访问该对象即可.

It is OK to pass a pointer to an object on the stack. Just make sure the user of that pointer does not access the object after its lifetime expires.

类或数组对于堆栈而言太大

the class or array is too big for the stack

仅在非常大的事情上才重要.您可能有1MB的堆栈,因此可以在出现问题之前放置大约1000个1KB的对象.

Only for really big things should this matter. You've probably got 1MB of stack, so you can put about 1000 1KB objects before there's a problem.

继承需要

为什么会这样?

还有其他东西吗?

something else?

对象所需的生存期长于堆栈框架的生存期.这是在堆上分配的主要原因.

The lifetime required of the object is longer than the lifetime of the stack frame. This is the principal reason to allocate on the heap.

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

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