我有一個關于向量、shared_ptr和復制c'tors的問題。
class Character
{
int health;//and more stuff that aren't important for this question。
//更多代碼...。
}
class Game
{
int size。
向量<shared_ptr<字符>>板。
當我這樣做時:
Game game1 = (53, ...)/say that I gave proper values for game1 to be constructed.
游戲game2 = game1。
什么會是game2中的向量?game2中的向量與game1中的向量有相同的地址嗎?還是說它是一個地址不同但內容相同的向量?
此外,如果我的問題的答案是它們是同一個向量(意味著它們有相同的地址),我怎樣才能使它們相互獨立?我想要的是兩個向量有相同的內容,但有不同的地址!
如果有人困惑,我可以讓它們相互獨立。
如果有人對我所說的內容感到困惑:它是向量內的共享_ptrs
。uj5u.com熱心網友回復:
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; //ptr1的拷貝,但是ptr2指向與ptr1相同的物件。
編輯。
因此,std::vector地址將是不同的,這意味著std::shared_ptr地址也將不同。只有,game1和game2中的Character物件將有相同的地址。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/314158.html
標籤:
