//Player.cpp
#include "Piece.h"
Piece* Player::addPiece (Chesspiece type)
{
Piece new_piece (type,this); //create new piece which points back to Player object
pieces.push_back (new_piece); //copy piece to vector of pieces held by Player
return pieces[pieces.size()-1].getPtr(); //once added return a pointer to the new piece
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14
//Piece.cpp
Piece::Piece (Chesspiece init,Player *parent)
{
moved = false;
taken = false;
type = init;
player = parent;
}
Piece* Piece::getPtr() //return pointer to Piece object
{
returnthis;
}
However, when I've tested this out:
1 2 3 4 5 6 7 8 9
int main()
{
Player test ("test",Bottom);
Piece* p1 = test.addPiece(Queen);
Piece* p2 = test.addPiece(Pawn);
std::cout << p1->getType()<<std::endl;
std::cout << p2->getType()<<std::endl;
}
I get the following output:
1 2
11754464
5
The first number is garbage (and varies every time) and the second number is correct.
Any ideas what I'm doing wrong? I suspect its something to do with the vector and that the pointer changes when its resized but would be grateful for any thoughts.
I've not tried this yet but should I create a vector of points to dynamically allocated Piece objects?
If you're storing pointers to elements in a vector, then yes, if adding an element to a vector results in a reallocation, those pointers are invalidated. The simplest solution would be to use a std::dequeue in place of the std::vector. You can probably drop that in without changing any other code.