Boost logo

Boost :

From: Greg Colvin (gcolvin_at_[hidden])
Date: 2001-07-24 14:42:54


From: Fernando Cacciola <fcacciola_at_[hidden]>
> From: Greg Colvin <gcolvin_at_[hidden]>
> > From: Peter Dimov <pdimov_at_[hidden]>
> > > From: <greg_at_[hidden]>
> > > > This looks like a good start, thanks. I think do_dynamic_cast is the
> > > > name we previously agreed on for your shared_dynamic_cast, and that
> > > > we wanted a version that worked for raw pointers as well.
> > >
> > > If do_dynamic_cast is supposed to be a generalization of dynamic_cast:
> > >
> > > template<class R, class T> R do_dynamic_cast(T /* const */ &);
> > >
> > > (dynamic_cast<U*> returns U*, dynamic_cast<U&> returns U&)
> > >
> > > then dynamic-casting a shared_ptr would look like
> > >
> > > do_dynamic_cast<shared_ptr<X> >(y); // 1
> > >
> > > whereas with a shared_ptr-specific cast the syntax would be
> > >
> > > shared_dynamic_cast<X>(y); // 2
> > >
> > > I prefer (2). (1) is more generic but I can't see how the genericity
> would
> > > be exploited.
> >
> > It could be exploited in generic code that didn't care whether
> > it was operating on raw pointers or smart pointers?
>
> Hmmm. I'm not sure if this is a desired behaviour.
> It is well known that mixing shared_ptr<T> and T* can lead to unexpected
> behavior. You have to do that carefully.
> Just as I like not being able to cast a shared_ptr<T> to a T* (I call get()
> if I really need to), I don't think I'd like a common
> interface to downcasting pointers.
> Don't get me wrong, I do support genericity as mush as possible, but in this
> area I'm not sure if both types can be generalized this much.

With the signatures Peter gives I don't you can use these to mix smart
pointers and raw pointers. And of course to use these in generic code
you would have to have typedefs for the pointer types to keep the same
syntax:

    template<typename BasePtr, typename DerivedPtr>
    DerivedPtr whatever(BasePtr in) {
       ...
       DerivedPtr p = do_dynamic_cast<DerivedPtr>(in);
       ...
       return p;
    }

An example might be a system that could use raw pointers and agarbage
collector, or else use smart pointers on systems where such a collector
was unavailable or inappropriate. I suppose for completeness one should
have do_static_cast and do_const_cast as well.

And of course this is just a workaround for the new-style cast operators
not being overloadable.


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