Is there a standard way to compare two references for identity implementing essentially what is done bellow:
bool compareForIdentity(int& a,int& b){return &a==&b;}
Reference equality means that two object references refer to the same underlying object.
In simple words: reference identity is memory address equality, as two variables points to the same content or not, like a postal address or a glass of water. Because references are hidden pointers to forget to manage them.
Most reference types should not overload the equality operator, even if they override Equals. However, if you are implementing a reference type that is intended to have value semantics, such as a complex number type, you should override the equality operator.
== and is are two ways to compare objects in Python. == compares 2 objects for equality, and is compares 2 objects for identity.
If you want to ensure that the references do not refer to the same object then yes, comparing the addresses as you have shown is indeed the standard way. The (built-in) address operator returns the address of the object referred to, not the address of the reference (which can conceptually be considered just another name without any object representation). This is the semantics usually needed to e.g. ensure a NOP for a copy to itself.
To ensure that indeed the built-in address operator is used (as opposed to any overloads) seems to be possible if a little tricky, cf. How can I reliably get an object's address when operator& is overloaded?.
Other uses may of course require different semantics, e.g. logical equality instead of physical.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With