user1599559
user1599559

Reputation:

C++: Create a copy of a pointer

I need to make a copy of GameMaster* thisMaster so I can preform manipulations while still maintaining a "clean" copy. However, the way I'm doing it right now, when I make a change to copy, it changes thisMaster too.

void Move::possibleMoves(GameMaster* thisMaster)
{
     GameMaster* copy = new GameMaster(*thisMaster);
}

How can I fix this?

edit: I created a copy constructor but am still having the same issue.

GameMaster::GameMaster(const GameMaster& gm)
{
    for(int i=0;i<GAMETILES;i++)
    {
        gameTiles[i]=gm.gameTiles[i];
    }
    players=gm.players;
    vertLines=gm.vertLines;
    horLines=gm.horLines;
    turn = gm.turn;
    masterBoard=gm.masterBoard;
    lastLegal=gm.lastLegal;
    lastScore=gm.lastScore;
}

Here is the complete class definition for GameMaster:

Class GameMaster
{
public:
    GameMaster(void);
    GameMaster(const GameMaster& gm);
    ~GameMaster(void);
    //functions

private:
    std::vector <Player*> players;
    std::vector <Line> vertLines;
    std::vector <Line> horLines;
    Tile gameTiles [GAMETILES];
    std::vector <std::string>colors;
    std::vector <std::string>shapes;
    int turn;
    Board masterBoard;
    bool lastLegal;
    int lastScore;
};

With the copy constructor, I am still having the issue with the Board changing values. Does it need a copy constructor too?

Upvotes: 3

Views: 6619

Answers (2)

jaybny
jaybny

Reputation: 1028

players=gm.players;

is only copying the collection of pointers.. you will need to do a deep copy of the players in the new vector.

edit

for( auto iter = gm.players.begin(); iter != gm.players.end(); ++iter) 
{
   players.push_back(new Players(*iter))
}

you will also need to have a copy const for Players.

cheers

Upvotes: 0

Class GameMaster
{
public:
    GameMaster(void);
    GameMaster(const GameMaster& gm);
    ~GameMaster(void);
    //functions

private:
    std::vector <Player*> players; // You should make a deep copy because of pointers
    std::vector <Line> vertLines; // Shallow copy is OK if Line doesn't have pointers in it
    std::vector <Line> horLines; // see above
    Tile gameTiles [GAMETILES]; // One by one assignment is OK
    std::vector <std::string>colors; // Shallow copy is OK
    std::vector <std::string>shapes; // Shallow copy is OK
    int turn; // assignment is OK
    Board masterBoard; // same questions for GameMaster still exists for copying this
    bool lastLegal; // assignment is OK
    int lastScore; // assignment is OK
};

Here is link for Shallow vs Deep copy

Upvotes: 2

Related Questions