The Spaceship Operator and Expression Rewriting

Defining the == Operator

Why do we need to explicitly define the == operator if we already have <=>?

Abstract art representing computer programming

The == operator is necessary even if we already have the <=> (spaceship) operator for a couple of reasons. Primarily, it comes down to performance and specific use cases.

Firstly, == is usually more efficient than <=>. When checking for equality, == can directly compare values, often using simpler operations.

On the other hand, <=> has to determine whether one value is less than, equal to, or greater than another, which can involve more complex logic.

For instance, comparing two strings for equality might only require a single operation if their lengths differ, whereas a three-way comparison would need to perform additional checks to determine the ordering.

Secondly, == is semantically clearer in many contexts. When you see == in code, you immediately understand that the check is for equality.

Using <=> for equality checks can make the code less readable and harder to understand at a glance, especially for those who may not be familiar with the spaceship operator.

Here's an example:

#include <compare>
#include <iostream>

class Number {
 public:
  std::strong_ordering operator<=>(
    const Number& Other) const {
    return Value <=> Other.Value;
  }

  bool operator==(const Number& Other) const {
    return Value == Other.Value;
  }

  int Value;
};

int main() {
  Number A{1};
  Number B{2};

  if (A == B) {
    std::cout << "A is equal to B";
  } else {
    std::cout << "A is not equal to B";
  }
}
A is not equal to B

In this example, operator== directly compares the values, while operator<=> handles the three-way comparison. By defining both, we ensure that equality checks are efficient and our intentions in the code are clear.

This Question is from the Lesson:

The Spaceship Operator and Expression Rewriting

A guide to simplifying our comparison operators using C++20 features

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

The Spaceship Operator and Expression Rewriting

A guide to simplifying our comparison operators using C++20 features

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved