• Advertisement
Sign in to follow this  

Comparing pointers?

This topic is 1926 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Lets say I have a method that looks like this:
[CODE]
void handleFooChange( Foo* a, Foo* b)
{
if( a == NULL || b == NULL || a == b )
return;
if( a->deleteFoo() )
delete a;
a = b;
}
[/CODE]
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 )

Share this post


Link to post
Share on other sites
Advertisement
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

[CODE]
Foo *newFoo = new Foo();

handleFooChange(oldFoo, newFoo);

// now oldFoo == newFoo
[/CODE]


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 [url="http://markgodwin.blogspot.com/2009/08/c-reference-to-pointer.html"]references to pointers.[/url] Like this.

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

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.

[CODE]
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;
}

[/CODE]

That is some of my feedback. Edited by HappyCoder

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement