我应该将整个对象或指向对象的指针存储在容器中吗?
从头开始设计新系统.我将使用STL存储某些长期存在的对象的列表和地图.
Designing a new system from scratch. I'll be using the STL to store lists and maps of certain long-live objects.
问题:我应该确保我的对象具有副本构造函数并将对象的副本存储在STL容器中,还是通常更好地管理生命周期?限制自己的范围,只是将指向这些对象的指针存储在我的STL容器中?
Question: Should I ensure my objects have copy constructors and store copies of objects within my STL containers, or is it generally better to manage the life & scope myself and just store the pointers to those objects in my STL containers?
我意识到这在细节上有些不足,但是我正在寻找理论上"的更好答案,因为它知道这两种解决方案都是可行的.
I realize this is somewhat short on details, but I'm looking for the "theoretical" better answer if it exists, since I know both of these solutions are possible.
使用指针有两个非常明显的缺点: 1)我必须自己在STL之外的范围内管理这些对象的分配/取消分配. 2)我无法在堆栈上创建一个临时对象并将其添加到我的容器中.
Two very obvious disadvantage to playing with pointers: 1) I must manage allocation/deallocation of these objects myself in a scope beyond the STL. 2) I cannot create a temp object on the stack and add it to my containers.
还有什么我想念的吗?
由于人们越来越喜欢使用指针的效率.
Since people are chiming in on the efficency of using pointers.
如果您正在考虑使用std :: vector且更新很少,并且您经常对集合进行迭代,并且它是一种非多态类型,则存储对象副本"会更有效,因为您将获得更好的引用位置.
If you're considering using a std::vector and if updates are few and you often iterate over your collection and it's a non polymorphic type storing object "copies" will be more efficent since you'll get better locality of reference.
Otoh,如果更新是常见的存储指针,则将节省复制/重定位成本.
Otoh, if updates are common storing pointers will save the copy/relocation costs.