cpp core · medium
The Spaceship Operator <=>
The C++20 three-way comparison operator <=> ('spaceship') returns an ordering object rather than a bool: comparing that result against literal 0 recovers <, <=, >, >=. Defaulting operator<=> compares members in declaration order and synthesizes all four relational operators, and a defaulted operator== adds == and !=, so two lines replace six. The return type names a comparison category: strong_ordering means equal values are fully substitutable (int, pointers); weak_ordering means values can be equivalent without being identical (case-insensitive strings); and partial_ordering allows 'unordered', as with floating-point NaN, where every comparison except != is false. Pick the category by what equality should mean and let the compiler generate the rest.
operator<=> returns an ordering you compare with 0, and = default synthesizes all six relational operators (with a defaulted == for equality); choose strong_ordering when equal means interchangeable, weak_ordering when merely equivalent, and partial_ordering when values can be unordered (NaN).
The code
struct Point { int x, y; auto operator<=>(const Point&) const = default; // synthesizes < <= > >= bool operator==(const Point&) const = default; // and == / !=};
(a <=> b) < 0 // means a < b — compare the ordering against 0 (a <=> b) == 0 // means a == b
1 <=> 2 // std::strong_ordering::less 0.0 / 0.0 <=> 1.0 // std::partial_ordering::unordered (NaN)What this lesson walks through
- 01<=> returns an ordering, not a bool
- 02Each relation is the ordering vs 0
- 03= default gives you all six
- 04strong_ordering: equal means identical
- 05weak_ordering: equivalent, not identical
- 06partial_ordering: some pairs are unordered
- 07Pick the category, default the operators
The three-way comparison operator <=> evaluates both operands once and returns an ordering object describing their relationship: less, equal, or greater. To get a yes/no answer you compare that ordering with literal 0.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of The Spaceship Operator <=> and 100+ animated C++ interview lessons.