Boost logo

Boost :

From: Kevlin Henney (Kevlin.Henney_at_[hidden])
Date: 2000-01-14 04:25:27


Braden N. McDaniel wrote:
>> Is there any way to downcast a shared_ptr? That is, the effect of
>>
>> shared_ptr<Base> base(new Base);
>
>Um. Oops. The above line should of course be
>
> shared_ptr<Base> base(new Derived);
>
>> shared_ptr<Derived> derived(base);

The short answer is "no, not at the moment". It is unlikely that you would
want such a narrowing conversion to be implicit: A keyword cast is probably
the most appropriate solution, eg

      template<typename Target, typename Source>
      inline shared_ptr<Target> dynamic_shared_cast(const
shared_ptr<Source> & arg)
      {
          shared_ptr<Target> result;

          if(Target * got = dynamic_cast<Target *>(arg.get()))
          {
              result.px = got;
              delete result.pn;
              ++*(result.pn = arg.pn);
          }

          return result;
      }

I recently raised this issue with Greg, who had been aware of it for some
time.

Kevlin


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