On Sep 16, 2025, at 07:53, Nate Eldredge via Std-Discussion <std-discussion@lists.isocpp.org> wrote:
On Sep 16, 2025, at 04:33, Andrey Semashev via Std-Discussion <std-discussion@lists.isocpp.org> wrote:
On 15 Sep 2025 16:48, David Brown via Std-Discussion wrote:
First ask yourself, is there any reason why you would want to compare
unrelated pointers for ordering?
One common use case is testing whether the pointers point to a subobject
of the same object. For example, if a pointer points within a string or
an array. This check is often needed to properly implement operations on
the string/array, such as selecting the direction of element iteration.
I don't actually think you can do this even with std::less. It's defined to use the implementation-defined strict total order over pointers (
https://eel.is/c++draft/defns.order.ptr); that has to be consistent with the < operator, but no other promises are made. So for instance, given `char foo[100];`, if we have `std::greater_equal<char *>{}(foo, p) && std::less<char *>{}(p, foo+3)`, I don't think the standard allows us to conclude that `p == foo || p == foo+1 || p == foo+2`. The converse holds, of course.
That should have been `std::greater_equal<char *>{}(p, foo) && std::less<char *>{}(p, foo+3)`.
Though for things like copying within a string, the converse is actually all you need. You can be certain that `std::less<char *>{}(p, foo) || std::greater_equal<char *>{}(p, foo+3)` implies `p != foo && p != foo+1 && p != foo+2`; i.e. that p does not point within that part of the array. So you can safely use std::less as a test for *potential* overlap, that will correctly detect overlap but may also have false positives. That wouldn't be a problem for correctness in typical algorithms, since the "overlap" code usually still works if the ranges don't overlap, just perhaps not as efficiently.