Comparing pointers?

Started by
2 comments, last by JohnnyCode 11 years, 6 months ago
Lets say I have a method that looks like this:

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 )
Advertisement
Yes, you can.

That code will correctly see if the two pointers both point to the same object.
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.
My current game project Platform RPG
If you compare value of two pointers. And the value match, it means pointers point to same memory. They apoint an object out there

This topic is closed to new replies.

Advertisement