简体   繁体   English

将对象或指针存储在矢量中

[英]Store Object or Pointer in a Vector

I asked a very similar question here but since it is such a fundamental issue I would like to state my (new) question more precicely. 我在这里问了一个非常相似的问题,但由于这是一个基本问题,我想更准确地陈述我的(新)问题。

Say I have a very complex class A and each instance of A is stored in multiple containers such as vectors, queues,... 假设我有一个非常复杂的A类,A的每个实例都存储在多个容器中,例如向量,队列,......

Even in a static setting, meaning that the objects get added to the containers once and will not be deleted nor modified: 即使在静态设置中,也意味着对象被添加到容器一次,不会被删除也不会被修改:
Should the containers now contain pointers to the objects or the objects itself? 容器现在应该包含指向对象或对象本身的指针吗?

If you need copies of objects - use objects. 如果需要对象的副本 - 使用对象。 If you need to share objects or polymorphic behavior is desired - use containers of smart pointers . 如果需要共享对象或需要多态行为 - 使用smart pointers容器。 In case of using smart pointers you will both have automatic object destruction and polymorphic behavior. 在使用智能指针的情况下,您将同时具有自动对象销毁和多态行为。

For example: 例如:

std::vector<std::shared_ptr<MyObject>> v;
auto ptr = std::shared_ptr<MyObject>(new MyObject());
v.push_back(ptr);

If you need to store unique pointers (with no sharing): 如果您需要存储唯一指针(不共享):

std::vector<std::unique_ptr<MyObject>> v;
auto ptr = std::unique_ptr<MyObject>(new MyObject());
v.push_back(std::move(ptr));

If each instance of A is stored in multiple containers, then you must store (smart) pointers instead of the objects themselves. 如果A每个实例都存储在多个容器中,那么您必须存储(智能)指针而不是对象本身。 Otherwise each container would have its own unique copy. 否则每个容器都有自己唯一的副本。 Modifying an instance in one container would not affect the others. 修改一个容器中的实例不会影响其他容器。 Even if you're not modifying anything, storing full object copies doesn't say what you mean , ie, that the instances across the containers are really the same. 即使您没有修改任何内容,存储完整的对象副本并不能说明您的意思 ,即容器中的实例实际上是相同的。

如果您的对象很大,或者复制成本高或复制起来很复杂,那么存储智能指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM