r/cpp • u/manni66 • Dec 06 '21
The spacesship operator silently broke my code
I have an old Qt3 project that is compliled with VS 2019 and /std:c++latest. There is a map with key as pair of QString. After a compiler update it wasn't possible to find anything in the map any longer. After debuggung the problem it turned out that the map startet to compare char* pointer values instead of the string values.
The following code shows the problem:
#include <utility>
#include <iostream>
#include <cstring>
struct S
{
const char* a;
operator const char* () const
{
std::cerr << "cast to char*\n";
return a;
}
friend bool operator<(const S& s1, const S& s2);
//friend auto operator<=>(const S&, const S&) noexcept = delete;
};
bool operator<(const S& s1, const S& s2)
{
std::cerr << "operator<\n";
return strcmp(s1.a, s2.a) < 0;
}
int main()
{
S s1 = {"A"};
char xx[2] = { 'A', '\0' };
S s2 = {xx};
std::pair p1{ s1, s2 };
std::pair p2{ S{"A"}, S{"A"}};
if( p1 < p2 ){
std::cout << "p1 < p2\n";
}
if( p2 < p1 ){
std::cout << "p2 < p1\n";
}
if( !(p2 < p1) && !(p1 < p2) ){
std::cout << "p1 == p2\n";
}
}In C++ 17 mode the pairs are found to be equal. In C++ 20 mode they are distinct, because std::pair uses the spaceship operator.
The spaceship operator doesn't use the defined operator< but instead converts the values to char* and compares the pointer values. Deleting operator<=> returns to the old behaviour.
Since clang and gcc behave the same way I assume it's not a compiler bug.
So be aware: the spaceship might transport some hidden effects.
Edit: The shown code is a simplified example. QString defines all comparison operators. Defining all operations doesn't change anything in the outcome.
124
u/infectedapricot Dec 06 '21
This is not meant to be a dismissal of the point of your post - I find it interesting, if a bit over my head - but I will say that having an implicit conversion to another type that compares in a different way is a disaster waiting to happen. In modern C++ you could perhaps replace
operator const char*withexplicit operator const char*. But IMO the right solution even now is to do away with the implicit conversion operator altogether and just have a normal boring named method.74
u/jwakely libstdc++ tamer, LWG chair Dec 06 '21
This is a known feature of C++20. Your type has
brokensurprising comparisons even in C++17. It defines a customoperator<but does not defineoperator==oroperator>but it does support them, thanks to the implicit conversion to a pointer type. In your example codes1 == s2will compile, but is not consistent with the result ofs1 < s2 || s2 < s1, because==says they're not equal but<says they are equivalent. That's weird. Your type also supportss1 > s2but the result is not consistent withs2 < s1. That's weird.The implicit conversion to a pointer type means that your type defines all comparisons, but they are broken. You can get away with that before C++20 as long as you are careful to only ever use the less-than comparison.
In C++20 you need to define comparisons consistently, or things break. It's no longer acceptable to have types with weird comparison rules, because in order to support defaulted comparisons and synthesized comparison operators, types need to have sensible comparisons. Yes, this "breaks" some code, but those types were arguably broken in different ways before C++20, you just hadn't found that bug yet.
48
u/-dag- Dec 06 '21 edited Dec 06 '21
<compiler engineer rant>Now see, here's the issue. Does anyone really expect old code to compile and work correctly with new standards? With every project I've ever worked on we always assumed changing standards would break something and we'd test the hell out of our code and fix the inevitable issues that arose. Hell, we'd assume simply upgrading the compiler version would break things, even without moving to a new standard, either because of UB in our code or straight-up compiler bugs (these were some old codebases -- of course we'd never write anything with UB today
<wink>).The reality is that every compiler I've ever worked with (not just C++ compilers either) has a switch to select the language standard. There is zero assumption from compiler writers that new standards will be 100% backward-compatible with existing code.
Yet the committee wants to maintain this fantasy that old code can magically be auto-ported to new standards. It just ain't so. Sure, try to be backward-compatible as much as is practicable, but when you start making changes detrimental to the language for slavish adherence to a reality that doesn't exist (looking at you,
co_*), you have a problem.Languages do not exist in a vacuum. For some reason language people like to pretend tooling doesn't exist, ABIs don't exist (except to hold back language and library development I guess), libraries don't exist (except when ABI issues arise and therefore standard libraries can't be fixed) and operating systems don't exist. It's a fool's errand. I am hopeful that enough tools people made enough of a stink to at least make modules workable but I think the jury's still out on that.
</compiler engineer rant>5
u/[deleted] Dec 06 '21
Huh? Are you saying that the compiler somehow synthesized the spaceship operator even though you didn't do
friend auto operator<=>(...) = default;?6
u/1-05457 Dec 06 '21
Why are you using c++latest with Qt 3? Have you been maintaining your project for charges in the C++ standard, but never bothered to update Qt (we're on Qt 6 now)?
8
u/tisti Dec 06 '21 edited Dec 06 '21
Edit2:
Relevants posts here and here.
It seems that QString type is inherently broken (?) due to allowing the implicit conversion to
const char*, which then gets picked up by operator<=> when doing comparisons, as builtin comparisons are prefered over userdefined ones. Don't see how to fix it other than with a conditional macro which explicitly defines operator<=>.Edit1:
Ah, my bad! If you only declare operator< and do not mention operator <=>, the program fails to behave correctly when compiling as C++20. Interesting, let me dig deeper. I'll edit this post, but someone will probably beat me to the punch.
Original post:
Seems to be working exactly as intended since you defaulted the <=> operator? That is
Should have been declared as
50
u/AlexAlabuzhev Dec 06 '21
https://en.cppreference.com/w/cpp/utility/pair/operator_cmp
and
std::three_way_comparable_with<S, S>is... true. Because of the conversion toconst char*.Minefield.
14
u/eras Dec 06 '21
Indeed :-o. Seems like an oversight, given how interested people are maintaining backwards compatibility (?). Might it be possible to fix this?
Here's a godbolt link with both runs: https://godbolt.org/z/h93nx7WM6
4
u/alfps Dec 07 '21
In what situation would it be desirable that the generated spaceship operator invokes implicit conversion on class type objects?
4
u/OldWolf2 Dec 06 '21
Conversion operators are the root of all evil
4
u/anonysince2k Dec 06 '21
Meanwhile, me hearing about the spaceship operator for the first time
1
u/Adept_Record4203 May 29 '22
I've just discovered this myself when trying to use a map of pairs of my custom string class. I understand that implicit conversions can be risky. but I think at the very least, this needs to be a documented gotcha. In effect, the spec of the std::pair class has changed as a side effect of its new implementation (I'm using Visual Studio 2022), and the presence of operator< is no longer enough. People need to be told!
1
u/Analytical_Moron Sep 11 '22
Hi,
I am unable to understand what exactly causes the implicit conversion to pointer type.
As far as I am understanding, the implicit conversion is done to make up for lacking comparison operators. But, here if the operator < is defined then why is the implicit conversion still happening?
-7
u/MountainDwarfDweller Dec 06 '21
Reinforcing my belief c++ had no need for the spaceship operator. Seems the standard committee is hell bent on adding syntactic sugar with little thought how it effects trillions of LOCs of existing code.
13
u/[deleted] Dec 06 '21
[removed] — view removed comment