Is there a major difference between passing a object through a function by reference vs creating a local reference variable and setting it equal to an object.
For context, state.clone() returns a std::unique_ptr to a OthelloGameState object. makeMove() is not a const function which is probably whats causing the segmentation fault when its being called on a const object.
For some reason when I create a local reference variable, set it equal to the cloned OthelloGameState, and call makeMove() I got a segmentation fault. Like I stated previous I am figuring this is because the object that is returned from state.clone() is still const which would cause a crash when I call makeMove() on it.
virtual std::pair<int, int> chooseMove(const OthelloGameState& state)
{
OthelloGameState& duplicateState = *state.clone();
duplicateState.makeMove(2,3);
return std::make_pair(0,0);
}
However, what is confusing to me is that I managed to fix this by passing it through a function by reference then calling the same makeMove() function on it. The code below works perfectly and I got no segmentation fault.
virtual std::pair<int, int> chooseMove(const OthelloGameState& state)
{
moveMe(*state.clone());
return std::make_pair(0,0);
}
void moveMe(OthelloGameState& state)
{
state.makeMove(2,3);
}
Is there a reason why calling makeMove() on a local reference would cause a segmentation fault, while passing it through a function first by reference then calling the same makeMove() function would work perfectly fine? I did the same experiment with pointers rather then reference and I got the same results.
Aucun commentaire:
Enregistrer un commentaire