Why do we need such an operator in C++ and how is it useful in modern C++ programming? Any real world code examples where this can be applied will help.
This question is geared to understand the practical application in real world without reading wordy proposal from Herb Sutter. No offense to the proposal though.
In PHP 7, a new feature, spaceship operator has been introduced. It is used to compare two expressions. It returns -1, 0 or 1 when first expression is respectively less than, equal to, or greater than second expression.
It's a general comparison operator. It returns either a -1, 0, or +1 depending on whether its receiver is less than, equal to, or greater than its argument.
The C++20 three-way comparison operator <=> (commonly nicknamed the spaceship operator due to its appearance) compares two items and describes the result. It's called the three-way comparison because there are five possible results: less, equal, equivalent, greater, and unordered.
I'll give you three points of motivation, just off the top of my head:
>
, >=
, ==
, <=
, <
. Using <=>
(spaceship), you can implement each of these other operations in a completely generic way.strcmp()
function from the C standard library. So - useful for lexicographic order checks, such as data in vectors or lists or other ordered containers.x86
or x86_64
Comparing a and b (CMP RAX, RBX
) is basically like subtracting (SUB RAX, RBX
) except that RAX
doesn't actually change, only the flags are affected, so you can use "jump on equal/not equal/greater than/lesser than/etc." (JE/JNE/JGT/JLT etc.) as the next instruction. CMP
should be thought of as a "spaceship compare".If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With