Re: Casting from void*
On Jun 28, 4:13 pm, Noah Roberts <d...@email.me> wrote:
On 6/25/2011 12:47 AM, Joshua Maurice wrote:
I did make the claim that "reinterpret_cast and static_cast between
them are equivalent." To be clear, the claim made was: for all types A
and B, for pointer b of type B*, the following two expressions are
equivalent:
static_cast<A*>(static_cast<void*>(b));
reinterpret_cast<A*>(b);
Are you sure about this?
No. Hence why I've been hedging my bets this whole time.
Correct me if I'm wrong:
A static cast to void* is guaranteed to create a pointer that points at
the beginning of the object. Thus:
struct X { ... };
struct Y { ... };
struct Z : X,Y { ... };
Y * ptr = new Z;
void * vptr = ptr;
Now ptr != vptr. Instead vptr == static_cast<X*>(ptr).
Then static_cast<A*>(vptr) can do the same sort of thing but in reverse
and on an unrelated tree of objects.
On the other hand, reinterpret_cast<A*>(ptr) == ptr no matter what the
inheritance looks like for either types.
Any of that in error?
Yes. You showed that
static_cast<void*>(static_cast<Y*>(new Z))
is not equivalent to
static_cast<void*>(static_cast<X*>(static_cast<Y*>(new Z)))
which was not my claim.
My claim again was that
static_cast<A*>(static_cast<void*>(new Z))
is equivalent to
reinterpret_cast<A*>(new Z)
which you did not address.
I again admit that I could be mistaken as a matter of fact, but on
most normal machines AFAIK that's what happens to be the case as a
matter of fact, and I would think you would need a malicious
implementation for it to be otherwise.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]