so I have a vector of pairs of pointers in c++:
vector<pair<Move *,Piece *> > moveList;
where Move is an object and Piece is an object…
Piece has the class variables type and side
so I add stuff to moveList:
pair <Move *, Piece *> pr (&m,&(p));
moveList.push_back(pr);
where m is a Move object and p is a Piece object
but whenever I call the moveList.back(), method, for some reason it would modify the values of Piece
so I do
Move * j = moveList.back().first;
Piece should have its "type" variable’s value set to ‘X’
but when I debug, it turns out that right after the line above, for some reason, Piece’s "type" variable’s value gets set to some crazy number such as -56 ‘\310’…..
what am I doing wrong?
EDIT
also moveList is set as a class variable
and the pushing into moveList and the getting the back() of moveList were done on different methods in that class
As others have pointed out, it’s seems you may be holding pointers to objects on the stack. These objects will go out of scope once you exit the function/block. Since STL containers manage their memory internally, one approach could be to change the vector to hold objects directly instead of pointers.
When the moveList object goes out of scope, it will automatically release the memory associated with the objects. In the case of pointers, you have to remember to manually deallocate the memory, else there will be a memory leak.