Comparison operator implementations like ==
or <=>
, despite not being hard to write, remain a source of bugs as
they must be updated with every change in the class’s member list. For instance, if the operation does not consider a newly introduced member in the
class, the issue will only manifest if two instances are identical, except for the freshly introduced member. As a consequence, this type of bug is
usually hard to spot.
C++20 introduced the ability to define both operator<=>
and operator==
as defaulted (= default
) to
indicate that they should consider all members in the order of their declaration. This makes code concise and makes all the comparison operators
resilient to the changes to the list of members. Thanks to operator rewriting, all other comparison operations (!=
, <
,
>
, <=
, =>
) can also rely on these robust operators.
Furthermore, when operator<=>
is defined as defaulted, the compiler will generate a defaulted version of operator==
if no other version is declared.