Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you compare objects by address for equality?

Tags:

c++

I have a function that compares objects by each attribute to see if they are identical. But I was just wondering, would it be better to compare the object by their address instead of checking if they are exactly same objects?

like image 713
user1527216 Avatar asked Sep 13 '12 09:09

user1527216


3 Answers

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

If you just want to know whether both references or pointers point to the same object (not identical objects, but the same), comparing the addresses is the right thing to do, indeed:

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 function template std::addressof is available to cope with that fact:

#include <memory> //std::addressof
bool AreEqual(const Class& a, const Class& b)
{
  return std::addressof(a) == std::addressof(b);
}
like image 114
Gorpik Avatar answered Nov 05 '22 17:11

Gorpik


You should decide whether your classes are meant to support equivalence or identity. Equivalence is a property typical of values, such as numbers. Identity is a property typical of entities, such as people.

Equivalence is usually determined by comparing the data members of a class; comparing addresses is a reasonable way to check for identity.

like image 23
Nicola Musatti Avatar answered Nov 05 '22 19:11

Nicola Musatti


I suppose that you make a proper distinction between same and equal.

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

Same attributes don't necessarily mean the same object. E.g. you can have two users with the same name "John Doe". The objects representing them would still be different objects, so they can't be used interchangeably. However, if you have a Point class, then two different instances of {1, 2} really represent the same thing and can be used interchangeably.

There is a larger issue of difference between value objects and reference objects or entities, so I suggest to look it up.

E.g. if you have a Point class, then two different instances of {1, 2} really represent the same thing, unlike the User example before.

like image 3
Zdeslav Vojkovic Avatar answered Nov 05 '22 18:11

Zdeslav Vojkovic