对象列表应该存储在堆还是栈上?

我有一个对象(A),它有一个由对象(B)组成的列表.list(B) 中的对象是指针,但列表本身应该是指针吗?我正在从 Java 迁移到 C++,但还没有完全习惯堆栈/堆.该列表不会传递到 A 类之外,只会传递列表中的元素.为了以防万一,将列表本身分配在堆上是一种好习惯吗?

I have an object(A) which has a list composed of objects (B). The objects in the list(B) are pointers, but should the list itself be a pointer? I'm migrating from Java to C++ and still haven't gotten fully accustomed to the stack/heap. The list will not be passed outside of class A, only the elements in the list. Is it good practice to allocate the list itself on the heap just in case?

另外,包含 list(A) 的类也应该在堆上吗?和列表一样,不会被传递.

Also, should the class that contains the list(A) also be on the heap itself? Like the list, it will not be passed around.

推荐答案

记住

  1. 只有当 Object-A 也在堆栈中时,列表才会在堆栈中
  2. 即使列表本身不在堆上,它也可以从堆中分配其存储空间.这就是 std::list、std::vector 和大多数 C++ 列表的工作方式――原因是基于堆栈的元素不能增长.
  3. 如今,大多数堆栈都在 1mb 左右,因此您需要一个相当大的对象列表才能担心它.即使您的堆栈只有大约 32kb,您也可以存储近 8000 个指针,以免成为问题.

不熟悉 C/C++ 中显式内存管理的 IMO 人员可能倾向于过度思考这些事情.

IMO people new to the explicit memory management in C/C++ can have a tendency to overthink these things.

除非您正在编写一些您知道会有数千个相当大的对象的东西,否则只需将列表放入堆栈中.除非您在函数中使用巨大的 C 样式数组,否则由于上面的 #1 和 #2,列表使用的内存可能最终会在堆中.

Unless you're writing something that you know will have thousands of sizable objects just put the list on the stack. Unless you're using giant C-style arrays in a function the chances are the memory used by the list will end up in the heap anyway due to #1 and #2 above.

相关文章