0

For assignment operator we check: if(this == &rhs), why not to check the same for self comparison in bool operator==(const MyClass& rhs)?

For assignment we want to avoid to self assign a bunch of data. The same is for comparison. If it is a good practice to check for assignment, then it should be for comparison too.

Narek
  • 38,779
  • 79
  • 233
  • 389
  • 3
    `s/we check/some of us sometimes check/` – juanchopanza Feb 05 '15 at 10:32
  • 3
    For assignment it may well be critical to check, whereas for comparison it would just be a (possibly premature) performance optimisation. – Paul R Feb 05 '15 at 10:32
  • 2
    You can do that if you want to and it makes sense. You can also not perform that check in the assignment operator when it's not necessary. – molbdnilo Feb 05 '15 at 10:34
  • 1
    "Self comparison is usually rare (...) Optimizing for rare cases is often a bad idea. It adds complexity to the code, and increases testing overhead." - from the [answer](http://stackoverflow.com/a/27281163/96780) to the [duplicate question](http://stackoverflow.com/q/27280601/96780). – Daniel Daranas Feb 05 '15 at 10:45
  • Probably related http://stackoverflow.com/questions/1691007/whats-the-right-way-to-overload-operator-for-a-class-hierarchy – SGrebenkin Feb 05 '15 at 10:49

1 Answers1

0

Because we usually associate == to check whether the data is exactly identical or not. this == &something checks whether they are pointers to the same thing or not.

#include <iostream>

struct A
{
    bool operator==(const A& rhs) const { return this == &rhs ; }

    int a ;
};

int main() {
    A a {2}, b{2};
    std::cout << std::boolalpha << (a == b);
    return 0;
}

The output of the above program is false even as a.a == b.a.

Here is the sample.

a_pradhan
  • 3,285
  • 1
  • 18
  • 23
  • You could check if the pointers are the same return true immediately. – Narek Feb 05 '15 at 10:52
  • That is what I am checking in this code. `this == &rhs` checks the pointers and yet it returns `false` and not `true` because they point to different objects. – a_pradhan Feb 05 '15 at 10:55