Given that A* pA; and B* pB;, is there ANY difference between below type castings (query for all C++ style casts):
pB = reinterpret_cast<B*>(pA); // pointer
pB = reinterpret_cast<B*&>(pA); // pointer-reference
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The two are radically different, at least in theory (and possibly on
a few rare machines, in practice). The first takes a pointer to A, and
converts it to a pointer to B; in theory, at least, this may involve
changes in size and representation. (I’ve actually worked on machines
where
char*was larger thanint*. I rather doubt that any suchmachines still exist, although perhaps in the embedded world…) The
second is really the equivalent of
*reinterpret_cast<B**>(&pA); ittakes the bits in
pA, and tells the compiler to interpret them asa
B*. If the format is different, tough luck, and if the size isdifferent, you’re likely to only access part of
pAor to access memorywhich isn’t part of
pA.Also, the first is an rvalue, the second an lvalue. Thus, something
like:
is illegal, but:
isn’t. This is a useful technique for obfuscating code, and getting
unaligned pointers, pointers into the middle of objects, or other
pointers you don’t dare dereference.
In general, the second form should be avoided, but there are rare
exceptions. Posix guarantees that all pointers, including pointers to
functions (but not pointers to members—Posix specifies a C ABI,
which doesn’t have pointers to members), have the same size and format,
so the second form is guaranteed to work. And it is the only way you
can legally convert the
void*returned bydlsyminto a pointer toa function:
(In C, you’d write:
, see the
official
specification.) Such tricks allow conversions between pointer types
which aren’t otherwise allowed, but depends on additional guarantees not
in the standard.