I have two pointers to objects and I want to test if they are the exact same object in the most robust manner. I explicitly do not want to invoke any operator ==
overloads and I want it to work no matter what base classes, virtual base classes and multiple inheritance is used.
My current code is this:
((void*)a) == ((void*)b)
And for my case this works. However, that doesn’t work for this case:
class B1 {};
class B2 {};
class C : public B1, public B2 {}
C c;
B1 *a = &c;
B2 *b = &c;
Subbing in reinterpert_cast
, static_cast
or dynamic_cast
doesn't work either.
Particularly I'm hoping for something that ends up really simple and efficient. Ideally it wouldn't require any branch instructions to implement and would do something like, adjust the pointer to the start of the object and compare.
If your classes are genuinely exactly as given then it's impossible as there's not enough information available at runtime to reconstruct the required information.
If they're actually polymorphic classes, with virtual functions, it sounds like dynamic_cast<void *>
is the answer. It returns a pointer to the most derived object. Your check would then be dynamic_cast<void *>(a)==dynamic_cast<void *>(b)
.
See paragraph 7 here:
http://www.csci.csusb.edu/dick/c++std/cd2/expr.html#expr.dynamic.cast
I suspect the usual dynamic_cast
issues apply -- i.e., no guarantee it will be quick, and your classes will have to be polymorphic.
This is not a feature I have used myself, I'm afraid -- but I have seen it suggested often enough by people who have that I infer it is widely-supported and works as advertised.