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

时间:2023-04-25
本文介绍了我应该存储整个对象,还是在容器中存储指向对象的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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

上一篇:为什么 std::cout 将 volatile 指针转换为 bool? 下一篇:为什么不在 C++ 中对所有内容都使用指针?

相关文章

最新文章