【问题标题】:making vectors of an object independent of each other使对象的向量相互独立
【发布时间】:2021-10-28 16:56:32
【问题描述】:

我有一个关于向量、shared_ptr 和复制 c'tors 的问题。

class Character 
{
     int health;//and more stuff that aren't important for the sake of this question
     //more code...
}

class Game 
{
     int size;
     vector<shared_ptr<Character>> board;
}

当我这样做时:

Game game1 = (53,...)//say that I gave proper values for game1 to be constructed.
Game game2 = game1;

game2 中的向量是什么? game2 中的向量是否与game1 中的向量具有相同的地址?还是地址不同但内容相同的向量?

此外,如果我的问题的答案是它们是相同的向量(意味着它们具有相同的地址),我怎样才能使它们彼此独立?我想要的是两个向量具有相同的内容但不同的地址!

如果有人对我所说的内容感到困惑:它是向量中的 shared_ptrs

【问题讨论】:

  • "game2 中的向量是什么?"试试看?
  • Game game2 = game1; 确实会创建game1 的副本,但由于boardstd::shared_ptr&lt;character&gt; 的向量,它所引用的地址仍然保持不变,因此如果您尝试访问共享指针,您将访问相同的位置。首先,你为什么还要使用vector&lt;shared_ptr&lt;character&gt;&gt;,为什么不直接使用vector&lt;character&gt;
  • 我会冒昧地说你问这个问题,因为你使用shared_ptr 作为“最佳实践”,然后看到两个游戏相互影响。这反过来又让你想知道为什么会这样。对此的实际答案是,您不应该在这里使用shared_ptr,因为您似乎并不想在Game 的实例之间共享任何数据。
  • @Ruks 做 {vector} 实际上会导致一些问题,因为有一堆类继承自 Character 并向这些特定类添加一些内部值,因此我使用 shared_ptr .
  • @StoryTeller-UnslanderMonica 确实我使用 shared_ptr 作为最佳实践,如果由我个人决定,我实际上会使用 unique_ptr 因为它更适合我的情况,但我我的教授强迫我使用 shared_ptr :(.

标签: c++ c++11 vector shared-ptr copy-constructor


【解决方案1】:

game2 将包含 game1 中向量的副本。它基本上会复制它所有的std::shared_ptr

但是,std::shared_ptr 的副本仅意味着内部引用计数将增加,它指向的对象将与原始 std::shared_ptr 中的对象相同。

例子:

std::shared_ptr<Character> ptr1 = std::make_shared<Character>();
std::shared_ptr<Character> ptr2 = ptr1; // Copy of ptr1, however ptr2 points to same object as ptr1

编辑: 因此,std::vector 地址将不同,这意味着std::shared_ptr 地址也将不同。只有Charactergame1 和 game2 中的对象具有相同的地址。

【讨论】:

  • 我知道,我的问题是,game2中棋盘向量的地址是否与game1中棋盘向量的地址相同
  • 向量的地址会有所不同。只有 Character 对象具有相同的地址。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-25
  • 1970-01-01
  • 2011-01-29
  • 2018-10-27
相关资源
最近更新 更多