Home >Backend Development >C++ >Why Doesn't a Custom `spaceship` Operator Generate `==` and `!=` Operators in C 20?

Why Doesn't a Custom `spaceship` Operator Generate `==` and `!=` Operators in C 20?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-07 05:35:02378browse

Why Doesn't a Custom `spaceship` Operator Generate `==` and `!=` Operators in C  20?

Non-Defaulted <=> Operator and the Absence of == and !=

In C 20, the newly introduced spaceship operator (<=>) has prompted some unexpected behavior regarding the generation of == and != operators. Users may encounter compilation errors when using a non-defaulted spaceship operator with custom implementations.

By default, the spaceship operator compares two objects of a given type. If a class does not explicitly define an == operator but does define a defaulted non-defaulted spaceship operator, the compiler will automatically generate an == operator with the same access as the spaceship operator. This behavior, specified in the language standard [class.compare.default], ensures that classes like std::vector do not use non-defaulted spaceship operators for equality tests.

However, if the spaceship operator is not defaulted (i.e., it has a custom implementation), the compiler will not generate an == operator. This is because classes that define custom spaceship operators may require specialized implementations for == to handle specific comparison scenarios. Thus, the language leaves it up to the programmer to define the == operator explicitly if needed.

For example, consider the following code:

#include <compare>

struct X
{
    int Dummy = 0;
    auto operator<=>(const X&) const = default; // Default implementation
};

This code compiles successfully because the spaceship operator is defaulted, and the compiler generates the == operator. However, if we change the spaceship operator to a custom implementation:

struct X
{
    int Dummy = 0;
    auto operator<=>(const X&amp; other) const
    {
        return Dummy <=> other.Dummy;
    }
};

The code will now fail to compile, with an error indicating that the == operator is not defined for class X. This is because the modified spaceship operator is not defaulted, and the compiler does not generate an == operator automatically. In this case, the user would need to explicitly define the == operator to address the comparison needs of their custom class.

The above is the detailed content of Why Doesn't a Custom `spaceship` Operator Generate `==` and `!=` Operators in C 20?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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