For some reason when I try and read a property of a pointer to an object(GamePlayer) within an std::list (playerlist) it works at first, but when I try to access it later in another function I get a bunch of random numbers instead of the numbers for my client’s socket. That was a mouthful, sorry. I hope someone could shed some light on the situation. I will include a simplified version of the defective code.
class GameRoom {
list<GamePlayer*> playerlist;
locigPort( LogicObj );
}
bool GameRoom::logicPort( LogicObj logit ) { // This is room[1]
list<GamePlayer*>::iterator it;
for (it = playerlist.begin(); it != playerlist.end(); it++){
cout << "socket numbers " << (*it)->socketno << endl;
/* (*it)->socketno gives me a bunch of random numbers,
not the socket numbers I was looking for! */
}
return true;
}
bool RoomDB::addPlayer( GamePlayer *playerpoint ) {
roomlist[1].playerlist.push_back( playerpoint );
// This adds the player object to the Gameroom object
cout << "player point " << playerpoint->socketno << " roomno: " << roomno;
// This shows everything should be ok so far
return true;
}
The most likely explanation is that you’re calling
addPlayerwith a pointer than becomes invalid by the time you calllogicPort. One possibility is that you calladdPlayerwith the address of an object on the stack, and the object disappears when the stack is unwound.edit The problem is right here:
PlayerDB::addPlayertakes the second argument by value. This means that it gets a copy that exists for the lifetime of the method. You then take the pointer to that copy, and add it to the list. OncePlayerDB::addPlayerreturns, the pointer becomes invalid.It’s hard to suggest a good fix without seeing more code. One possibility is to make
PlayerDB::addPlayertake a pointer as its second argument, and make sure you don’t repeat the same mistake one level up the call chain.An even better possibility is to turn
playerlistintolist<GamePlayer>: from your code there doesn’t appear to be any need for the list to contain pointers. This will simplify things greatly.