Sep 29, 2011 at 8:07pm UTC
Hey,
I would like to know whether it is good practice to use Pointer addresses to check whether two class instances are the same. E.g.:
1 2 3 4 5 6
Foo x;
Foo *p1 = &x;
Foo *p2 = &x;
if (p1 == p2) std::cout << "Same instance" ;
Can this get me into trouble at some point or are pointer addresses in fact completely static during runtime? I need this to find elements in a list for example.
Thanks for any help!
Best,
Henning
Last edited on Sep 29, 2011 at 8:09pm UTC
Sep 29, 2011 at 8:12pm UTC
It's safe, the address of an object never changes after it has been created.
Sep 29, 2011 at 8:56pm UTC
This was commonly done in assignment operators to prevent assignment to ones self. Modern approaches use the copy and swap idiom for exception safety.
Last edited on Sep 29, 2011 at 8:57pm UTC