Boost logo

Boost :

From: Fernando Cacciola (fcacciola_at_[hidden])
Date: 2002-04-24 15:26:49


"Peter Dimov" <pdimov_at_[hidden]> wrote in message
news:000901c1ebb0$907e91f0$1d00a8c0_at_pdimov2...
> From: "Fernando Cacciola" <fcacciola_at_[hidden]>
> > "Peter Dimov" <pdimov_at_[hidden]> wrote in message
> > news:000501c1eb7a$0f4a2760$1d00a8c0_at_pdimov2...
> > > I've changed the shared_ptr(T *) constructor to a member template,
> > > template<class Y> shared_ptr(Y *).
> > >
> > I've just looked at it.
> >
> > Why is the cast from Y* to T* implicit?
>
> I'm not sure I understand the question.

Maybe you're right and I just didn't sleep enough :-), but..

> What other kind of cast is
> applicable? If you write
>
> T * p = new Y;
>
> there must exist a conversion from Y* to T*, right?
>
Yes, a conversion for which the compiler might require RTTI.

> shared_ptr<T> p(new Y);
>
> is similar.
>
> > AFAIK this could go wrong when complex polymorphism is involved:
> >
> > shared_ptr<Base> pb( new Derived ) ;
>
> How could this go wrong?
>
>
The conversion from Derived* to Base* might require a pointer fixup. This
requires RTTI. C++ doesn't force the use of RTTI unless dynamic_cast<> is
used, so the implicit conversion could go wrong in exactly the same way a
C-style cast could go wrong if the conversion requires pointer value
adjustment.

IOWs, the template constructor acts exactly like a C-style cast between
arbitrary pointers. If dynamic_cast<> isn't required in this situation, then
when is it?

> > My own smart ptr has both template and non template ctors.
> > The template ctor uses boost::polymorphic_cast.
>
> And doesn't work for non-polymorphic types; this may be considered a
> feature, of course.
>
Exactly! I think that initalization of shared_ptr<T> from Y should be
accepted only iif T and Y belongs to the same hirearchy.

> > > This breaks some existing code since '0' is no longer an acceptable
> > > argument; for instance, px.reset(0) needs to be rewritten as
px.reset().
> > >
> > I think this could be resolved by having both template and non-template
> > versions.
>
> I don't want to resolve it. ;-) The new behavior is better.
>
OK.

--
Fernando Cacciola
Sierra s.r.l.
fcacciola_at_[hidden]
www.gosierra.com

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