问题
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.
回答1:
I'll give you three points of motivation, just off the top of my head:
- It's the common generalization of all other comparison operator (for totally-ordered domains):
>
,>=
,==
,<=
,<
. Using<=>
(spaceship), you can implement each of these other operations in a completely generic way. - It's incredibly useful for strings: For that specific case, it's the good old
strcmp()
from the C standard library. So - useful for anything with lexicographic order, such as data in vectors or lists or other ordered containers. - For integral numbers, it's what the hardware does anyway: On
x86
orx86_64
Comparing a and b (CMP RAX, RBX
) is basically like subtracting (SUB RAX, RBX
) except thatRAX
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".
来源:https://stackoverflow.com/questions/49661170/why-do-we-need-the-spaceship-operator-in-c