Jump to content

  • Log In with Google      Sign In   
  • Create Account


#ActualHappyCoder

Posted 12 October 2012 - 03:29 PM

You can compare pointers and mentioned before but the last line in your function isn't doing anything.


I expect you wanted to be able to do something like this

Foo *newFoo = new Foo();

handleFooChange(oldFoo, newFoo);

// now oldFoo == newFoo


but in reality oldFoo is unchanged because it retains its pointer to old object. When you passed oldFoo to the function the pointer is copied into another memory location so when you assign a = b, you change the value of a, but oldFoo is unaffected because it resides in a different place in the memory, even though oldFoo and a both point to the same object.


I don't know if you care about that or not but I thought I would mention that. You could fix this by making the parameters references to pointers. Like this.

void handleFooChange( Foo *& a, Foo *& b)
{
if( a == NULL || b == NULL || a == b )
  return;
if( a->deleteFoo() )
  delete a;
a = b;
}

Pointer logic be confusing at times so I would personally avoid this situation and try to come up with a solution that doesn't require double pointers, references to pointers, ect. I personally would refactor the code to look like this.

bool didFooChange( Foo* a, Foo* b)
{
if( a == NULL || b == NULL || a == b )
  return false;
else
  return true;
}

// then use it like this
if (didFooChange(oldFoo, newFoo))
{
  delete oldFoo;
  oldFoo = newFoo;
}


That is some of my feedback.

#1HappyCoder

Posted 12 October 2012 - 03:28 PM

You can compare pointers and mentioned before but the last line in your function isn't doing anything.


I expect you wanted to be able to do something like this

Foo *newFoo = new Foo();

handleFooChange(oldFoo, newFoo);

// now oldFoo == newFoo


but in reality oldFoo is unchanged because it retains its pointer to old object. When you passed oldFoo to the function the pointer is copied into another memory location so when you assign a = b, you change the value of a, but oldFoo is unaffected because it resides in a different place in the memory, even though oldFoo and a both point to the same object.


I don't know if you care about that or not but I thought I would mention that. You could fix this by making the parameters references to pointers. Like this.

void handleFooChange( Foo *& a, Foo *& b)
{
 if( a == NULL || b == NULL || a == b )
  return;
 if( a->deleteFoo() )
  delete a;
 a = b;
}

Pointer logic be confusing at times so I would personally avoid this situation and try to come up with a solution that doesn't require double pointers, references to pointers, ect. I personally would refactor the code to look like this.

bool didFooChange( Foo* a, Foo* b)
{
 if( a == NULL || b == NULL || a == b )
  return false;
 else
  return true;
}
// then use it like this

if (didFooChange(oldFoo, newFoo))
{
  delete oldFoo;
  oldFoo = newFoo;
}


That is some of my feedback.

PARTNERS