C++ operator ==, is it important to check self equality?

Given the the following code

1
2
3
4
5
6
bool Foo::operator==(const Foo& other) {
if (this == &other) {
return true;
}
return name == other.name && size == other.size;  
}



Is it so important to check is it the same object like in code above? If yes than why?
Last edited on
It's not necessary. Line 5 will work fine if you compare the same object to itself. The only reason I can think of for checking is for performance reasons, but comparing an object to itself is rare so it might not be worth it.
+1 Peter87

also note that this example is missing a const qualifier, so it will fail to compile when called with a const argument on the left (common error, and one of the motivational examples for the default comparisons proposal, which, by the way, does not specify a self-comparison check)
For operator==, it doesn't matter so much as Cubbi and Peter87 have said, but for operator= (assignment) it's usually critical.
> for operator= (assignment) it's usually critical.

In modern C++, it is usually not required.
The special case (where a check for self-assignment is required for lvalues) is when we want to optimally reuse existing resources held by the target of the assignment.

Copy-and-swap idiom: https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Copy-and-swap

The unified assignment operator with non-throwing swap - canonical and exception-safe:
1
2
3
4
5
T& T::operator=(T arg) // copy/move constructor is called to construct arg
{
    swap(arg); // resources are exchanged between *this and arg
    return *this;
} // destructor of arg is called to release the resources formerly held by *this 


http://en.cppreference.com/w/cpp/language/operators
Topic archived. No new replies allowed.