Can you compare objects by address for equality?

I have a function that compares objects for each attribute to make sure they are identical. But I was just wondering if it would be better to compare the object at their address, rather than checking if they are exactly the same objects?

+6
source share
4 answers

You must decide whether your classes should support equivalence or identity. Equivalence is a property typical of values ​​such as numbers. Identity is a property typical of entities such as humans.

Equivalence is usually determined by comparing class member data; comparing addresses is a smart way to authenticate.

+12
source

EDIT: Beware: you cannot pass values ​​(objects) to your function if you want it to work correctly. You need to pass either (possibly const) links or pointers.

If you just want to know if both links or pointers point to the same object (not identical objects, but the same thing), then address comparison is really what you need to do:

bool AreEqual(const Class& a, const Class& b) { return &a == &b; } 

Note that the & operator may be overloaded for the Class Class above. Since C ++ 11, the std::addressof function template is available to handle this fact:

 #include <memory> //std::addressof bool AreEqual(const Class& a, const Class& b) { return std::addressof(a) == std::addressof(b); } 
+13
source

I believe that you are making the right distinction between the same and equal.

Two pointers pointing to the same address mean that they point to the same object. So yes: the same address means the same object and therefore equal (although equality only makes sense if we are talking about more than 1 object).

The same attributes do not necessarily mean the same object. For instance. you can have two users with the same name "John Doe". The objects that represent them will still be different objects, so they cannot be used interchangeably. However, if you have a Point class, then two different instances of {1, 2} do represent the same thing and can be used interchangeably.

There is a big problem of the difference between the values ​​of objects and reference objects or persons , so I suggest looking at it.

eg. if you have the Point class, then two different instances of {1, 2} really represent the same thing, unlike the previous user example.

+3
source

If you have objects for which the comparison takes a lot of time, comparison of pointers can be used as a quick way to determine the equivalence of an object (i.e. if the pointers are equal, the objects are equivalent, otherwise they can be equivalent)

+2
source

Source: https://habr.com/ru/post/925295/


All Articles