Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Standard way to compare references for identity

Tags:

c++

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;}
like image 262
George Kourtis Avatar asked Sep 01 '14 20:09

George Kourtis


People also ask

What is reference equality?

Reference equality means that two object references refer to the same underlying object.

What is reference identity?

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.

Is it safe to use the equality operators to compare reference types?

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.

How do you compare objects in Python?

== and is are two ways to compare objects in Python. == compares 2 objects for equality, and is compares 2 objects for identity.


1 Answers

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.

like image 142
Peter - Reinstate Monica Avatar answered Nov 15 '22 01:11

Peter - Reinstate Monica