Search code examples
c++pointerstype-traitscomparison-operators

When are two pointers comparable?


There so many questions on comparing two pointers, but I found none on whether the two types are such that the pointers can be compared. Given

A* a;
B* b;

I want to know if expression a @ b is valid, where @ is one of ==,!=,<,<=,>,>= (I don't mind about nullptr_t or any other type that can be implicitly converted to a pointer). Is it when A, B are

  • equal?
  • equal except for cv-qualification?
  • in the same class hierarchy?
  • ...?

I didn't find anything in std::type_traits. I could always do my own SFINAE test, but I am looking for the rules to apply them directly. I guess that will be easier for the compiler, right?

EDIT To clarify again: I am comparing pointers, not objects pointed to. I want to know in advance when a @ b will give a compiler error, not what will be its value (true or false or unspecified).


Solution

  • C++ Standard

    5.9 Relational operators

    Pointers to objects or functions of the same type (after pointer conversions) can be compared, with a result defined as follows:

    — If two pointers p and q of the same type point to the same object or function, or both point one past the end of the same array, or are both null, then p<=q and p>=q both yield true and p<q and p>q both yield false.

    — If two pointers p and q of the same type point to different objects that are not members of the same object or elements of the same array or to different functions, or if only one of them is null, the results of pq, p<=q, and p>=q are unspecified.

    — If two pointers point to non-static data members of the same object, or to subobjects or array elements of such members, recursively, the pointer to the later declared member compares greater provided the two members have the same access control (Clause 11) and provided their class is not a union.

    — If two pointers point to non-static data members of the same object with different access control (Clause 11) the result is unspecified.

    — If two pointers point to non-static data members of the same union object, they compare equal (after conversion to void*, if necessary). If two pointers point to elements of the same array or one beyond the end of the array, the pointer to the object with the higher subscript compares higher.

    — Other pointer comparisons are unspecified. §