我应该存储整个对象,还是在容器中存储指向对象的指针?

Should I store entire objects, or pointers to objects in containers?(我应该存储整个对象,还是在容器中存储指向对象的指针?)
本文介绍了我应该存储整个对象,还是在容器中存储指向对象的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

从头开始设计新系统.我将使用 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.

这篇关于我应该存储整个对象,还是在容器中存储指向对象的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Could I ever want to access the address zero?(我可以想访问地址零吗?)
C++ Access derived class member from base class pointer(C++ 从基类指针访问派生类成员)
Weird Behaviour with const_cast(const_cast 的奇怪行为)
Are pointer variables just integers with some operators or are they quot;symbolicquot;?(指针变量只是带有某些运算符的整数还是“符号?)
Modifying a char *const string(修改 char *const 字符串)
Modifying a const int in C++(修改 C++ 中的 const int)