Compare void pointers in constexpr

Viewed 44

In C++:

  1. It's OK to convert pointers to void* without a cast
  2. It's OK to have 1-past-end pointers as long as you don't dereference them
  3. It's OK to compare pointers with == and != even though they point to unrelated objects.

In that case, why does this fail to compile:

consteval int test() {
    int* a = new int(42);
    long* b = new long(43);

    void* pa = &a + 1;
    void* pb = &b;


    int res = 0;
    if (pa == pb) res = 1;

    delete a;
    delete b;
    return res;
}  

int main() {
    return test();
}

Clang says:

subexpression not valid in a constant expression
    if (pa == pb) res = 1;

And GCC says:

 error: '(((void*)(&& test::a[1])) == ((void*)(& b)))' is not a constant expression
   10 |     if (pa == pb) res = 1;
      |         ~~~^~~~~

Neither is particularly useful. As far as I can tell, no UB is involved here. Is there a way to compare these pointers for equality without upsetting the compilers?

0 Answers
Related