Skip to main content
GameDev.net gamedev.net
🔒 Locked

Epiphany (pointer comparison)

Started by jamesleighe Oct 20, 2011 at 12:31 AM 3 replies 1.2k views
Original Post
jamesleighe
jamesleighe
So, pretty much I can sum this up in code.


void FindThingInArray (Thing* thing)
{
for (uint32 i = 0; i < vector.Count (); ++i)
{
if (vector->GetID () == thing->GetID ())
return i;
}
}


Notice in the second one, I'm just comparing pointers!

void FindThingInArray (Thing* thing)
{
for (uint32 i = 0; i < vector.Count (); ++i)
{
if (vector == thing)
return i;
}
}


This should work in all cases (where the pointers point to the same thing) right?
It seems too useful to be true.

My test program seems to work fine but is there some reason I shouldn't do this? (before i convert over loads of code)
jameszhao00
jameszhao00
Yes. C++ 's find

And also watch out. Using pointers as object identities may lead to issues down the road (serialization/deserialization, network, ...)
smasherprog
smasherprog
also, check out your return type. Currently, it is void, but it should be something else.
Wisdom is knowing when to shut up, so try it.
--Game Development http://nolimitsdesigns.com: Reliable UDP library, Threading library, Math Library, UI Library. Take a look, its all free.
latent
latent

but is there some reason I shouldn't do this?


Only if there's a chance you are comparying a *copy* of the object. ie...

[source lang="cpp"]
Thing b = *vector;
return FindThingInArray(&b); //fails in your second example, but succeeds in your first
[/source]
Vectorian
Vectorian
Yes this always works. A 'common' issue with this beside the serialization etc. already mentioned is that you cannot replace instances if you use pointers as identifiers (ie. swap one object for another (most often of different derived types)).

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.