Date: Tue, 16 Sep 2025 13:53:59 +0000
> On Sep 16, 2025, at 04:33, Andrey Semashev via Std-Discussion <std-discussion_at_[hidden]> 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.
> Really, the language already defines the logic under the name of
> std::less. Why the same logic cannot be invoked as the built-in
> operrator< for pointers?
That's what I and others have answered: operator< can be more efficient because it is not required to handle the case of pointers to unrelated objects, and there are implementations where handling this case carries substantial extra cost.
>
> 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.
> Really, the language already defines the logic under the name of
> std::less. Why the same logic cannot be invoked as the built-in
> operrator< for pointers?
That's what I and others have answered: operator< can be more efficient because it is not required to handle the case of pointers to unrelated objects, and there are implementations where handling this case carries substantial extra cost.
Received on 2025-09-16 13:54:03