TITLE: static_cast and reinterpret_cast (Newsgroups: comp.std.c++, 11 Feb 97) MASHLAN: rmashlan@r2m.com (Robert Mashlan) >|> >Assuming that type T2 has stricter or equal alignment restrictions >|> >than type T1, Is it possible that the following two expressions >|> >return different results? >|> > >|> > T2* pt2; >|> > >|> > T1* pt1 = static_cast(static_cast(pt2)); >|> > >|> >vs. >|> > >|> > T1* pt1 = reinterpret_cast(pt2); CLAMAGE: Stephen.Clamage@eng.sun.com (Steve Clamage) writes: >|> It is always possible for static_cast and reinterpret_cast to produce >|> different results, because the results of a reinterpret_cast are >|> implementation-defined. >|> >|> The example static_cast above is invalid if T1 and T2 are unrelated >|> types, which they appear to be. The compiler must issue a diagnostic. KANZE: James Kanze >Something I don't understand: how does the fact that T1 and T2 are or >are not related affect the static_cast's in the example? There is no >direct static_cast between the two classes, only to and from void*. CLAMAGE: Sorry, I was compressing two things into one sentence. Here's an expanded version. In the submitted example, the cast to void* loses type information that might be important. The casts might do the right thing, but you can't depend on it. (For example, if T1 and T2 are part of the same hierarchy, the T1 and T2 sub-objects have the same address, and the pointers have the same representation, the cast will work. It will probably also work for unrelated pointer types which have the same representation, given the alignment preconditions.) Contrarywise, a cast like static_cast(pt2) might be valid if T1 and T2 are part of the same hierarchy, but not otherwise. (It is valid if T1 is a base class of T2, or if T2 is a non-virtual base class of T1.) KANZE: >(This leads to a further question: is a static_cast FROM void* legal? >Should it be?) CLAMAGE: Yes, since a static cast can reverse most implicit conversions. (I think the only exception is reversing a conversion to a virtual base class.) In particular, you can static_cast any data pointer to void* and back to the original type and get a pointer that compares equal to the original.