Can you compare objects by address for equality?

前端 未结 4 2040
旧时难觅i
旧时难觅i 2021-02-13 13:58

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 inste

相关标签:
4条回答
  • 2021-02-13 14:22

    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);
    }
    
    0 讨论(0)
  • 2021-02-13 14:28

    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.

    0 讨论(0)
  • 2021-02-13 14:39

    If you have objects for which comparison is time consuming, comparing the pointers could be used as a fast way to determine object equivalence (i.e., if the pointers are equal, objects are equivalent, otherwise they may still be equivalent)

    0 讨论(0)
  • 2021-02-13 14:43

    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.

    0 讨论(0)
提交回复
热议问题