C++20 allows heap allocation in constexpr functions as long as the memory does not leak. However GCC and Clang disagree on whether comparing the addresses of two dynamically allocated objects is a constant expression or not.
The following snippet can be compiled with Clang but not gcc.
constexpr bool foo() {
int* a = new int(4);
int* b = new int(4);
bool result = a == b;
delete a;
delete b;
return result;
}
constexpr bool x = foo(); // GCC: error: '(((int*)(& heap deleted)) == ((int*)(& heap deleted)))' is not a constant expression
The following works fine on both compilers
constexpr bool foo2() {
int a = 4;
int b = 5;
bool result = &a == &b;
return result;
}
constexpr bool x = foo2();
I'd assume that in order to delete the dynamic objects correctly the compiler must know whether the pointers point to the same objects or not, so I'd assume this is a GCC bug (or not yet fully implemented). Can anyone confirm this assumption? Or am I wrong?
Live example here.
Edit: Strangely, when I open the live example through the link provided, it suddenly compiles on gcc, too. But if I copy-paste it to a new compiler explorer instance, it fails again. Or if I reload it multiple times it fails every second time and compiles every other second time...