Search code examples
c++qtc++14visual-studio-2019void-pointers

pointer equality test with same address yields false


Why is this pointer comparison not working?

// in handleSlot()...
void* ptr1 = m_expected; // defined as SimpleBase*
void* ptr2 = sender(); // defined as QObject*
if (ptr1 != ptr2)
    return; // this should not be reached, since the debugger shows ptr1 and ptr2 are the same

The background here is that I have a templated type which inherits from both QObject and T, where T is a subclass of SimpleBase. Since I don't know which template instantiation has triggered the slot, I can't do a dynamic cast here to directly compare pointers of the same type.

I also tried comparing the pointer addresses using reinterpret_cast<uintptr_t>, but when I did that oddly enough they yielded different integers.

I was able to workaround the problem by adding an argument to the signal and slot so that it passes const SimpleBase * i.e. this, and the pointer comparison works that way. But I am curious if there is a way to compare these pointers as they were, using sender() instead of passing the extra argument?


Solution

  • It seems you can dynamic_cast<SimpleType*>(sender()) or dynamic_cast<QObject*>(m_expected) assuming both are unique and have a virtual function. Multi-inherited bases do have different actual addresses and you can’t compare them for equality using void* always.