First, I admid that I only read the code in the link diagonally. Apparently, the Handle class overloads the dereferencing operator (*
) to return the T*
that is being handled. Thus, the expressions in the first line mean the following:
this
is a (possibly cv-qualified) Handle<T> * const
.
*this
is Handle<T> &
**this
is the return value of the handle's operator*
, which is the T*
you mentioned.
- Finally, that
T*
is reinterpreted into a void**
. Note that one extra indirection is added, so dereferencing the result is possible and will yield a void* &
instead of a T&
- The equivalent line with
that
yields a S*
that is reinterpreted as a void**
.
Thus, you get a couple of pointers to different types T*
and S*
that are magically reinterpreted as void**
. Then the code performs null checks and then, the magic line:
return *a == *b;
Which is comparing the (possibly unaligned!) first sizeof(void*)
bytes of the objects of types T
and S
that are actually pointed to by a
and b
. Unless you can be completely sure that T
and S
have the proper size and alignment, the check is completely bogus. For example, the check would make sense if you know that T
itself is always a pointer or smart pointer object with the same size of a pointer, so you may have different handles point to different pointer objects that nevertheless point (in the 2nd indirection level) to the same object. This allows the GC to move the underlying object without having to update all handles to it, by simply updating the contents of the 1st level pointers.
Handle<T> has T* -----> T = U* pinned in memory -----> actual object U can be moved
So, to answer your question, casting only to void*
(without increasing the indirection) is not the same as making the check in the code - your version would compare the pointers, so in my example, two different handles to the same object might compare unequal with your alternate code.
PS: it is also bad style to have your class return T*
from both operator*
and operator->
, because then you are breaking the general identity between p->x
and (*p).x
. The de-referencing operator should generally return a T&
if the member access operator returns a T*
.
Handle<T>
yields aT*
, then this code is deeply flawed, as the comparison generates both false positives and false negatives: Ifsizeof(T) < sizeof(void*)
you get false negatives because stuff that does not belong to the objects is included in the comparison, and ifsizeof(T) > sizeof(void*)
you get false positives because only the first four/eight bytes of the objects get compared.