Should "operator! =" Always be implemented via "operator ==" in C ++?

I am currently browsing the old C ++ codebase and see that a lot of code looks like this:

bool SomeClass::operator==( const SomeClass& other ) const
{
   return member1 == other.member1 && member2 == other.member2;
}

bool SomeClass::operator!=( const SomeClass& other ) const
{
   return member1 != other.member1 || member2 != other.member2;
}

it is clear that the comparison logic is duplicated, and the code above will probably have to be changed in two places, and not in one.

AFAIK typical implementation method is operator!=as follows:

bool SomeClass::operator!=( const SomeClass& other ) const
{
    return !( *this == other );
}

In the latter case, any change in logic occurs in operator==, it is automatically reflected in operator!=, because it simply causes operator==and executes the negation.

Is there any resonant case when it operator!=should be implemented in any other way than just reuse operator==in C ++ code?

+3
4

a!=b !(a==b).

: a<b !(a=>b) !(a==b || a>b) a<=b && !(a==b) .. ..

boost.operators .


, (.. ==, , , - , STL, >> <<) .

, , , STL .


EDIT - :

, , . , a!=b !(a==b), :

  • , , boost.operators:
    bool operator!=(a,b) { return !(a==b); }

  • .

. , , , , , : ( boost.operators, , NRVO, , , NRVO).

, , , , ( : , ).

+9

!= ==. ( )

+4

- , operator!= , operator== ++?

. , . postfix ++ ++ ( , , , , , ), operator + operator += ( , ).

std::relops .

+3

semantically yes (which means that == should be a logical complement! =), but in practice (coding) you do not need to.

+2
source

Source: https://habr.com/ru/post/1784920/


All Articles