【发布时间】: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的副本,但由于board是std::shared_ptr<character>的向量,它所引用的地址仍然保持不变,因此如果您尝试访问共享指针,您将访问相同的位置。首先,你为什么还要使用vector<shared_ptr<character>>,为什么不直接使用vector<character>? -
我会冒昧地说你问这个问题,因为你使用
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