This is the mail archive of the gcc-patches@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: C++ PATCH: throw (T *)NULL and dynamic_cast


On Sep  1, 1999, Jason Merrill <jason@cygnus.com> wrote:

> In a dynamic_cast, you know whether the target type T has the source type V
> as a public base.  If it doesn't, you don't need to bother looking for a
> downcast.

Unless you don't call the following example a downcast (would you call
it a sidecast? :-), it will break:

struct V { virtual ~V() {} };
struct T {};
struct X : T, V {};
int main() {
    X x;
    V *v = &x;
    T *t = dynamic_cast<T*>(v);
    if (! t) abort();
}

It should be valid, according to [expr.dynamic.cast]/8:

  --Otherwise, if v points (refers) to a public base class sub-object of
    the most derived object, and the type of the most derived object has
    an unambiguous public base class of type T, the result is a  pointer
    (an  lvalue  referring)  to  the  T  sub-object  of the most derived
    object.


> Furthermore, if T has V as an unambiguous public non-virtual base,
> we know what the answer will be if the downcast succeeds.  So we
> calculate the answer we want, and if we find a subobject of type T
> at that address, we're done.

This sounds somewhat dangerous.  Assume:

struct B { int foo; };
struct V { virtual ~V() {} };
struct T : B, V { virtual void bar() {} };
struct X : V {};

// mmap_X returns a pointer to an X object that lives in the beginning
// of a page, and the previous page is not mapped.
V *v = mmap_X();

// This might access the unmapped page when checking whether v is-a T.
T *t = dynamic_cast<T*>(v);

Unless I'm missing something about the way this test would be
performed.

-- 
Alexandre Oliva http://www.dcc.unicamp.br/~oliva IC-Unicamp, Bra[sz]il
oliva@{dcc.unicamp.br,guarana.{org,com}} aoliva@{acm.org,computer.org}
oliva@{gnu.org,kaffe.org,{egcs,sourceware}.cygnus.com,samba.org}
** I may forward mail about projects to mailing lists; please use them


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]