Boost logo

Boost :

From: GregAMartin_at_[hidden]
Date: 2001-05-19 02:24:00


Rainer,

Thank you for your feedback. I had added the dynamic cast as an
after thought without thinking it through.

I was wanting to get by without making a copy of the shared pointer,
but after your comment about it not being "safe" as far as the
Standard is concerned I started thinking and realized that compilers
are allowed to do any manner of magic when downcasting or upcasting
classes so not allowing the compiler to truly typecast the object
pointer contained within the smart pointer would not be portable even
if it did work for my platform. Of course, you may be referring to
something else that I'm not even thinking of.

Still, if it does work for my platform I might go ahead and use it
since it does bypass an unnecessary smart pointer construction.

But it is obviously "wrong" and my first template lasted less than 12
hours of scrutiny. Oh, well, I posted it here to get feedback. I'll
go and crawl back under my rock and wait for my pride to heal (grin).

Greg

--- In boost_at_y..., "Rainer Deyke" <root_at_r...> wrote:
> ----- Original Message -----
> From: <GregAMartin_at_E...>
> To: <boost_at_y...>
> Sent: Friday, May 18, 2001 4:51 PM
> Subject: [boost] Re: downcasting smart pointers
>
>
> > Templates:
> >
> > template<typename T, typename U>
> > inline shared_ptr<T>& sp_static_cast(const shared_ptr<U>& a)
> > { static_cast<shared_ptr<T>::element_type*>(
> > static_cast<shared_ptr<U>::element_type*>( 0 ) );
> > return *(shared_ptr<T>*)&a; }
>
> This is of course completely unsafe as far as the Standard is
concerned, but
> I can't really imagine a compiler on which 'shared_ptr<T>' and
> 'shared_ptr<U>' have different memory layouts, so it might be fine
in
> practice.
>
> > template<typename T, typename U>
> > inline shared_ptr<T>& sp_dynamic_cast(const shared_ptr<U>& a)
> > { dynamic_cast<shared_ptr<T>::element_type*>(
> > static_cast<shared_ptr<U>::element_type*>( 0 ) );
> > return *(shared_ptr<T>*)&a; }
>
> This, on the other hand, is completely broken. Consider the
following:
>
> class A {};
> class B : public A {};
>
> A a;
> B *bp = dynamic_cast<B *>(&a);
>
> The correct value if 'bp' at this point is '0'. Your function does
not
> mirror this behavior. The following fixes that problem:
>
> template<typename T, typename U>
> inline shared_ptr<T>& sp_dynamic_cast(const shared_ptr<U>& a)
> {
> if (dynamic_cast<T *>(a.get()) {
> return *(shared_ptr<T>*)&a;
> }
> return shared_ptr<T>(0);
> }
>
>
> --
> Rainer Deyke (root_at_r...)
> Shareware computer games -
http://rainerdeyke.com
> "In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" -
Abigor


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