Boost logo

Boost :

From: Steven Watanabe (steven_at_[hidden])
Date: 2007-10-10 15:38:40


AMDG

Martin Bonner <Martin.Bonner <at> pi-shurlok.com> writes:

>
> From: Simonson, Lucanus J
>
> > There are cases where reading
> > the C++ standard will inform a developer that reinterpret_cast is safe
> > [snip]. Specifically, I submit that inheritance and
> > composition are such cases
>
> As I said in my previous email, I don't think so. BUT...
>
> > provided that additional data members are not
> > added in the subtype or composed type.
>
> ... I missed this.
>
> I still don't think the standard makes the guarantees you think it does,
> but in practise, you are much less likely to run into problems with that
> limitation.
>
> If the types are inherited (rather than composed) I still think you have
> problems if the derived class overrides virtuals in the base.
>

Even without overriding virtuals, technically such a cast is wrong.

"If a nonstatic member function of a class X is called for an object
that is not of type X, or of a type derived from X, the behavior is
undefined." (9.3.1/1)

In other words, you can do the reinterpret_cast to and from
the derived class, and that is guaranteed to work, but you
cannot call a member function and cast the this pointer
back to the base.

While what you are doing will probably work I can imagine
a case where the compiler helpfully inserts code for
detecting such a cast (Since for non-aggregates the compiler is
permitted to add extra hidden members)

In Christ,
Steven Watanabe


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk