Can you compare nullptr to other pointers for order? Is it always smaller?

∥☆過路亽.° 提交于 2020-12-08 06:54:24

问题


This question is based on code that I found that monitors possible memory leaks, so it contains some code that you probably don't want to see in regular programs like ordering pointers.

However, I saw that a pointer was set to nullptr and then the pointer was compared to a maximum address. Is it guaranteed by the C++ standard that nullptr is always smaller than other pointers for operator<?


回答1:


Can you compare nullptr to other pointers for order?

Yes. But whether the result is useful is another matter.

Is it always smaller?

No. Unless the other operand is also null, neither operand is guaranteed to compare greater or smaller in this case.

Standard quote (latest draft):

[expr.rel]

The result of comparing unequal pointers to objects is defined in terms of a partial order consistent with the following rules:

  • [does not apply] If two pointers point to different elements of the same array, or to subobjects thereof, the pointer to the element with the higher subscript is required to compare greater.
  • [does not apply] If two pointers point to different non-static data members of the same object, or to subobjects of such members, recursively, the pointer to the later declared member is required to compare greater provided the two members have the same access control ([class.access]), neither member is a subobject of zero size, and their class is not a union.
  • [applies] Otherwise, neither pointer is required to compare greater than the other.

You should use std::less to compare pointers if you need a strict total order. Null is still technically not guaranteed to compare as smallest value, although cases where it isn't are probably rare in practice and I don't know if there are modern C++ implementations for such systems.




回答2:


No. Less-than comparisons involving a nullptr do not have specified behavior, and while they do not involve undefined behavior the results are not even guaranteed to be consistent.

The guarantees provided by < on pointers are extremely limited. Even comparing two separately heap-allocated objects is not guaranteed to be consistent (for that you need std::less, which will consistently place a null pointer somewhere in the ordering but not at a standard-defined place). The best you can say is that no pointer to an object will compare equal to a nullptr.



来源:https://stackoverflow.com/questions/65185742/can-you-compare-nullptr-to-other-pointers-for-order-is-it-always-smaller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!