Can you compare objects by address for equality?

前端 未结 4 2034
旧时难觅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  //std::addressof
    bool AreEqual(const Class& a, const Class& b)
    {
      return std::addressof(a) == std::addressof(b);
    }
    

提交回复
热议问题