Given the example from cppreference on <=>
, we can simplify the example code to:
struct person {
std::string name;
std::string surname;
auto operator <=> (const person& p) const {
if (const auto result = name <=> p.name; result != 0) {
return result;
} else {
return surname <=> p.surname;
}
}
};
But my IDE (CLion 2020.2), via clang-tidy, warns that result != 0
should actually be result != nullptr
. I didn't know that we can compare std::###_ordering
with nullptr
. Cpprefence also claims that we should rather compare it with literal 0
. There is nothing about nullptr
there.
This code:
int main() {
person p1{"ccc", "vvv"};
person p2{"aaa", "zzz"};
std::cout << (p1 < p2);
}
compiles (GCC 10.1.0, Rev3, Built by MSYS2 project) and yields identical results to both the 0
and the nullptr
version.
However, my IDE also warns me that I should "Clang-Tidy: Use nullptr" with p1 < p2
. By applying the "fix", the code changes to std::cout << (p1 nullptr p2);
which, well, doesn't compile. It hints that it may be a bug in clang-tidy, but it doesn't explain why we can compare the orderings with nullptr
. Why we can, why does it work and why would we want that?
nullptr
in your posted code.. – Blackburn0
and thenullptr
version." - I meant that if we actually replaceif (const auto result = name <=> p.name; result != 0)
withif (const auto result = name <=> p.name; result != nullptr)
, the code compiles and yields the expected results. – Toughienullptr
instead of0
. Barry covered the topic in his answer pretty well. It's not about parsing, it's about clang-tidy and actualy compilers (suggesting) and accepting this. – Toughieoperator <
,auto operator <=> (const person& p) const { return std::tie(name, surname) <=> std::tie(p.name, p.surname); )
:) (or even= default;
here ;) ) – Garrick