Boost logo

Boost :

From: Rainer Deyke (root_at_[hidden])
Date: 2001-05-18 21:03:49

----- Original Message -----
From: <GregAMartin_at_[hidden]>
To: <boost_at_[hidden]>
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

> 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_[hidden])
Shareware computer games           - 
"In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor

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