1
votes

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.

1
Please don't post images of code. - user2100815
*state.clone() does memory leak (or if you use smart pointer, that creates dangling pointer). - Jarod42
If you work for a company like mine that blocks imgur using images of your code makes your question unreadable. - NathanOliver
@NathanOliver you're not missing much - M.M
It is throroughly irrational to post pictures of text, or links to them. (1) It is much more work than posting the text; (2) it wastes bandwidth of readers; and (3) it prevents cut and paste for use in comments and answers. Don't do it here. - user207421

1 Answers

4
votes

The unique_ptr created by state.clone() is destroyed at end of expression. So your reference/pointer is dangling.

Use instead:

auto cloned = state.clone();
cloned->makeMove(2, 3);