C++ – Understanding the <=> (Spaceship) Operator in C++

c++c++20operatorsspaceship-operator

While I was trying to learn about C++ operators, I stumbled upon the following table that listed a strange comparison operator. What does this <=> operator do?

2017 image of a table from cppreference.com
Since 2017 cppreference.com updated that page and now contains detailed information about the<=>operator.

Best Answer

This is called the three-way comparison operator.

According to the P0515 paper proposal:

There’s a new three-way comparison operator, <=>. The expression a <=> b returns an object that compares <0 if a < b, compares >0 if a > b, and compares ==0 if a and b are equal/equivalent.

To write all comparisons for your type, just write operator<=> that returns the appropriate category type:

  • Return an _ordering if your type naturally supports <, and we’ll efficiently generate <, >, <=, >=, ==, and !=; otherwise return an _equality, and we’ll efficiently generate == and !=.

  • Return strong if for your type a == b implies f(a) == f(b) (substitutability, where f reads only comparison-salient state accessible using the nonprivate const interface), otherwise return weak.

The cppreference says:

The three-way comparison operator expressions have the form

lhs <=> rhs   (1)  

The expression returns an object that

  • compares <0 if lhs < rhs
  • compares >0 if lhs > rhs
  • and compares ==0 if lhs and rhs are equal/equivalent.