C ++ STL:应该存储整个对象还是指向对象的指针? [英] C++ STL: should I store entire objects, or pointers to objects?

查看:248
本文介绍了C ++ STL:应该存储整个对象还是指向对象的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从头开始设计新系统。我将使用STL存储某些长效对象的列表和地图。

Designing a new system from scratch. I'll be using the STL to store lists and maps of certain long-live objects.

问题:我应该确保我的对象有复制构造函数,并存储对象的副本我的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.

使用指针的两个非常明显的缺点:$ b​​ $ b 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.

're考虑使用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.

这篇关于C ++ STL:应该存储整个对象还是指向对象的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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