Use of Pointer Addresses to compare Class Instances

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
It's safe, the address of an object never changes after it has been created.
Great - thx Athar!
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
Topic archived. No new replies allowed.