Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't built-in relational operators for pointer types generate a total order in C++?

I am aware that relational operators for pointers give reliable results only in limited cases, and they are not guaranteed to generate a total order. However, standard function objects for those operators do have specializations which generate a total order.

So what's preventing the same rule applying for built-in operators? That doesn't seem to simplify anything, since reliable comparison is still needed (by some implementation-specific method) for those function objects to work.

Furthermore, is it possible do reliable comparison on pointers with only built-in operators? Although it looks like impossible, I would like to confirm it here.

like image 696
hpsMouse Avatar asked Nov 27 '12 09:11

hpsMouse


1 Answers

It's not that they don't generate a total order, but simply that they are not guaranteed to do so. In practice, they typically will obey a total ordering on most modern hardware. It's just not guaranteed by the standard.

Of course, an implementation could always force them to do so, but then it comes down to the C++ guiding principle, "you don't pay for what you don't use". On some CPUs it may be more expensive to do that.

Suppose you have a CPU with a more complex address model, like, say, a segmented address space. In that case, it is no longer quite as trivial to determine if one pointer is "greater than" another. So the C++ standard allows for both: the "usual" weak pointer comparison rules only guarantee a total ordering for certain limited cases (basically, when pointers point into the same array, which is guaranteed to be linear and sequential and can be implemented very efficiently), and wrapper functions such as std::less which on some CPUs may be more expensive, but which do guarantee a total ordering for all pointers.

like image 181
jalf Avatar answered Nov 07 '22 21:11

jalf