Home > Backend Development > C++ > body text

Why Doesn't the Non-defaulted Spaceship Operator Generate `==` and `!=` in C 20?

Linda Hamilton
Release: 2024-11-07 22:13:03
Original
222 people have browsed it

Why Doesn't the Non-defaulted Spaceship Operator Generate `==` and `!=` in C  20?

Why Non-defaulted Spaceship Operator Doesn't Generate == and !=

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.
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!