你能比较 nullptr 和其他指针的顺序吗?它总是更小吗?

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

这个问题基于我发现的监控可能的内存泄漏的代码,因此它包含一些您可能不希望在常规程序(如排序指针)中看到的代码。

然而,我看到一个指针被设置为nullptr,然后指针与最大地址进行比较。 C++ 标准是否保证 nullptr 总是小于 operator< 的其他指针?

Can you compare nullptr to other pointers for order?

不,您不能对 nullptr 或其他空指针常量与指针进行有序比较。


对于我的其余回答,我涵盖了 “你能比较 具有空值 的指针与其他指针的顺序吗?”

。但是结果有没有用就是另外一回事了

Is it always smaller?

没有。除非另一个操作数也为空,否则在这种情况下,两个操作数都不能保证比较大或小。

标准报价(最新稿):

[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.

如果你需要严格的全序,你应该使用std::less来比较指针。 Null 仍然不能保证作为最小值进行比较。

没有。涉及 nullptr 的小于比较没有指定的行为,虽然它们不涉及未定义的行为,但结果甚至不能保证一致。

< 对指针提供的保证非常有限。即使比较两个单独堆分配的对象也不能保证是一致的(因为你需要 std::less,这将始终如一地将空指针放在 某处 的排序中,而不是在某个位置标准定义的地方)。你能说的最好的是,没有指向对象的指针会将 equal 与 nullptr.

进行比较

nullptr is always smaller than other pointers for operator<

否,标准不支持通过关系运算符将 nullptr 与指针进行比较。

要比较关系运算符的操作数,首先将以下规则应用于两个操作数,即 expr.rel#2

The usual arithmetic conversions are performed on operands of arithmetic or enumeration type. If both operands are pointers, pointer conversions and qualification conversions are performed to bring them to their composite pointer type. After conversions, the operands shall have the same type.

nullptr不是指针,而是空指针常量。因此,“执行指针转换和限定转换以将它们转换为复合指针类型”将不适用于它。因此,它违反了,转换后,操作数应具有相同的类型

Clang给出了正确的诊断。由于代码格式错误,因此谈论结果是什么没有意义。