void handleFooChange( Foo* a, Foo* b)
{
if( a == NULL || b == NULL || a == b )
return;
if( a->deleteFoo() )
delete a;
a = b;
}
Where Foo is an abstract class/interface that a and b inherits from. Can you compare two pointers like this ( See if they are pointing to the same memory adress i.e the same object )
3 replies to this topic
#1 Members - Reputation: 233
Posted 12 October 2012 - 10:02 AM
Lets say I have a method that looks like this:
Sponsor:
#3 Members - Reputation: 682
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
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.
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.
That is some of my feedback.
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.
Edited by HappyCoder, 12 October 2012 - 03:29 PM.






