I am trying to make a board game, since every move has to be valid, so I am making a copy of board and make a move so I can verify if that move is valid or not.
First I initialize all the positions on the board to be 0 (iterate through the board and set every p to 0
pair<int, int> p(y, x);
board_[p] = 0;
This is the copy board method
void Board::copy(Board & gb) {
for (int y = MIN_Y; y <= MAX_Y; ++y) {
for (int x = MIN_X; x <= MAX_X; ++x) {
pair<int, int> p(y, x);
if (gb.board_.at(p) != 0) {
board_[p] = new Pieces(*gb.board_.at(p)); // **where I am confused**
} else {
board_[p] = 0;
}
}
}
}
My container in Board is:
map<pair<int,int>, Pieces*> board_;
Now in a play method, I make a copy of the board
unsigned int play(Board & b){
b.copy(*this);
}
My question: both
board_[p] = new Pieces(*gb.board_.at(p)); //Pieces is a class I defined
and
board_[p] = gb.board_.at(p);
compile without any errors or warnings. Which one should I use though?
Either may be correct, but you probably want the first one. The first will copy each of the
Piecesover to the new board – this is known as a deep copy. The second will only copy the pointers to eachPiecesover, so both boards point at the same set ofPieces– this is a shallow copy.However, there is a bigger issue here. You are defining a
copyfunction, but C++ gives us a language feature for doing this – copy constructors. You should instead define a function like so:And you would use it like so: