Home > Net >  making vectors of an object independent of each other
making vectors of an object independent of each other

Time:09-17

I have a question regarding vectors, shared_ptr, and copy 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;
}

When I do this:

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

What would be the vector that's in game2? Does the vector in game2 have the same address as the vector in game1? Or is it a vector with a different address but the same contents?

Moreover, if the answer to my question is that they're the same vector (meaning they have the same address), how can I make them independent of each other? What I want is for both vectors to have the same contents but different addresses!

If anyone is confused by what I mean with contents: it's the shared_ptrs inside the vector

CodePudding user response:

game2 will contain copy of vector in game1. It will basically copy all its std::shared_ptr.

However, copy of std::shared_ptr means only, that internal ref count will be incremented, object which it points to will be the same as in the original std::shared_ptr.

Example:

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

EDIT: Thus, std::vector addresses will be different, which means that also std::shared_ptr addresses will be different. Only, Character objects in game1 and game2 will have same addresses.

  • Related