|
Boost Users : |
Subject: Re: [Boost-users] shared_ptr downcast
From: Jason Cipriani (jason.cipriani_at_[hidden])
Date: 2008-12-23 05:01:38
On Tue, Dec 23, 2008 at 4:54 AM, Jason Cipriani
<jason.cipriani_at_[hidden]> wrote:
> Research is showing this isn't possible. I'm sure there's a good
> reason for it... but I need to get this working. I came up with this
> hack that works but is scary. Assuming there is no virtual inheritance
> involve (this would have the same semantics as reinterpret_cast):
>
>
> template <typename Dest, typename Src>
> shared_ptr<Dest> shared_reinterpret_cast (const shared_ptr<Src> &src) {
>
> shared_ptr<Src> hack(src);
> shared_ptr<Dest> dest;
>
> assert(sizeof(hack) == sizeof(dest));
> char buf[sizeof(dest)];
>
> // swap dest and hack
> memcpy(buf, &dest, sizeof(dest));
> memcpy(&dest, &hack, sizeof(dest));
> memcpy(&hack, buf, sizeof(hack));
>
> return dest;
>
> }
>
Scratch that, this seems safer:
template <typename Dest, typename Src>
shared_ptr<Dest> shared_reinterpret_cast (const shared_ptr<Src> &src) {
shared_ptr<Src> hack(src);
return *(shared_ptr<Dest> *)&hack;
}
The first attempt would cause problems if shared_ptr's implementation
stored a pointer to itself, for some reason, or gave it's address to
some other shared_ptr.
Jason
>
> It's really dirty, but will it work OK? The basic idea is to swap a
> new shared_ptr<Base> with an empty shared_ptr<Derived>, but bypass
> shared_ptr::swap()'s type checking.
>
> Jason
>
>
> On Tue, Dec 23, 2008 at 4:36 AM, Jason Cipriani
> <jason.cipriani_at_[hidden]> wrote:
>> If I have:
>>
>> class Base { };
>> class Derived : public Base { };
>>
>> And a container, e.g.:
>>
>> std::vector<boost::shared_ptr<Base> > objs;
>>
>> How do I downcast to a shared_ptr<Derived>? E.g.:
>>
>> boost::shared_ptr<Derived> d = (boost::shared_ptr<Derived>)objs[0];
>>
>> I have a function that takes a shared_ptr<Derived> and all I have is a
>> shared_ptr<Base>. I don't mind static_cast behavior, although
>> dynamic_cast behavior would be ideal.
>>
>> Thanks,
>> Jason
>>
>
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net