Archived

This forum has been archived. Please start a new discussion on GitHub.

operator== of C++ classes

in the documentation's section C++ mapping for classes, it says

operator==
operator!=
operator<
operator<=
operator>
operator>=
The comparison operators permit you to use classes as elements of STL sorted containers. Note that sort order is based on the data members of the class, as for structures (see Section 6.12).


But when I tried to use it and looked into the source code, it turns out the current implementation merely conpairs the two pointers.
My question is, is it going to be implemented in the future or was it an old feature and won't be there any more? I just happen to need this now and it seems impossible to get around the problem except to write my own member-wise comparison code.

Comments

  • marc
    marc Florida
    You must be looking at an old version of the manual. (I think this was a bug in the manual, but it has been fixed for quite some time now.)

    Have a look at http://www.zeroc.com/doc/Ice-3.2.0/manual/Cpp.7.14.html (last sub-chapter):
    As for proxy handles (see Section 6.11.3 on page 210), class handles support the comparison operators ==, !=, and <. This allows you to use class handles in STL sorted containers. Be aware that, for smart pointers, object identity is not used for the comparison, because class instances do not have identity. Instead, these operators simply compare the memory address of the classes they point to. This means that operator== returns true only if two smart pointers point at the same physical class instance:

    [...]
  • marc
    marc Florida
    Oops... I just noticed that we indeed still have this sentence in the manual:
    The comparison operators permit you to use classes as elements of STL sorted containers. Note that sort order is based on the data members of the class, as for structures (see Section 6.12).

    That's a bug in the manual. The paragraph I cited above is the correct one. Slice classes have reference semantics, not value semantics, therefore it compares instances, not values. See also this thread for a similar discussion.
  • thanks! That clarifies a lot.

    I guess you should remove the == operator that takes two references (if that's easy to do). The paragraph you referenced above only talks about class handle compison, and that's intuitive to understand given that it's name is smart POINTER. What i did is

    class A {...};

    int main()
    {
    APtr a = new A;
    APtr b = new A(a);
    cout<< (*a==*b); <-- :D this still only compares address
    }