When using the new spaceship operator (<=>) in C 20, it's crucial to note the implications of implementing a custom operator versus relying on the default implementation.
In the first example, you're using the default operator<=> implementation provided by the language. This default implementation allows the compiler to automatically generate an == operator. However, when you implement a custom operator<=> function, the compiler can no longer implicitly generate a corresponding == operator.
This behavior is intentional, as stated in the C standard ([class.compare.default](https://en.cppreference.com/w/cpp/language/comparison#Class_comparison)):
If the class definition does not explicitly declare an == operator function, but declares a defaulted three-way comparison operator function, an == operator function is declared implicitly with the same access as the three-way comparison operator function.
The reason behind this design choice is to prevent the implicit generation of == in situations where it may not be the most efficient way to determine equality. For example, classes like std::vector should not use a non-defaulted <=> for equality tests because comparing sizes first is more efficient.
In a custom <=> implementation, the class may be performing specialized operations that require a custom implementation for == as well. Therefore, instead of generating a potentially non-optimal default implementation, the language leaves it up to the programmer to define the == operator explicitly.
The above is the detailed content of Why Doesn't the Non-defaulted Spaceship Operator Generate `==` and `!=` in C 20?. For more information, please follow other related articles on the PHP Chinese website!