Boost logo

Boost :

From: Simonson, Lucanus J (lucanus.j.simonson_at_[hidden])
Date: 2007-10-11 19:05:30

Martin wrote:
>I don't think that's true. Given:
> class Base {....}
> struct Derived : public Base{ int DerivedFunction(); };
> Base b;
> Derived* pDerived = static_cast<Derived*>(&b);
> pDerived->DerivedFunction(); // Undefined behaviour.
>The behaviour of the call to DerivedFunction is not defined by the
>standard. (Of course, on many compilers today it will do what the
author >expected.)

The reason it is categorized as undefined is because Derived may extend
Base by adding data members, inheriting from another base, or adding a
virtual pointer. My contention was that the behavior when none of those
conditions is true is defined, or at least implicitly defined. What I
mean by implicitly defined is that if X is true, and Y is true then we
can infer that Z must also be true. This happens in specs all the time.

Steven wrote:
>Yes but casting to a derived sub-object that doesn't exist
>yields undefined behavior when you attempt to call a non-static
>member function of the derived class.

If I have Base and Derived types the compiler has to ensure correct
execution when given the clearly standard compliant usage:

Derived object;
Base& baseRef = object;
Derived& derivedRef = static_cast<Derived&>(baseRef);

ergo it must implicitly support:

Base base;
Derived& derivedRef = static_cast<Derived&>(base);

provided that Derived does not modify Base by multiple inheritance,
adding a member or a virtual pointer, because it can't prove that
derivedRef is not an alias for the pointer to base because it could be
that derivedRef is an alias for baseRef as part of the standard
compliant usage.

I can make a similar argument for composition based upon the fact that
the compiler can't prove statically that a pointer to an object type
that is the same type as a data member of another class is not in fact
an alias for an object of that other class's type.

If a compiler optimization can be proven to break standard compliant
code it is safe to assume that such compiler optimization won't happen,
or at least will be rolled back immediately.


Boost list run by bdawes at, gregod at, cpdaniel at, john at