kamikaze_pilot
kamikaze_pilot

Reputation: 14844

c++ vector of pairs of pointers screw up

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

Upvotes: 2

Views: 5283

Answers (2)

Peter G.
Peter G.

Reputation: 15144

There's not enough code to say for sure, but a wild guess is you created the objects on the stack and the stack frame they lived in is no longer alive. In this case one fix is to allocate the objects from the heap, like so:

Move * move = new Move;
Piece * piece = new Piece;
moveList.push_back( make_pair(move, piece) );

I didn't address exception safety in this example for clarity and brevity.

Edit

A possible idiomatic solution that addresses memory management and exception safety can be achieved by using smart pointers:

typedef pair< shared_ptr<Move>, shared_ptr<Piece> > MovePiece;
vector< MovePiece > moveList;
moveList.push_back( MovePiece(make_shared<Move>(), make_shared<Piece>()) );

Upvotes: 2

AK.
AK.

Reputation: 763

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.

vector <pair <Move, Piece> > moveList;
// To insert
moveList.push_back (make_pair <Move, Pair> (move, pair));

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.

Upvotes: 6

Related Questions