Boost logo

Boost :

From: Greg Colvin (gcolvin_at_[hidden])
Date: 2001-03-18 11:18:12


From: Eric Ford <eford_at_[hidden]>
> I'm using the counted_ptr from http://ootips.org/yonat/4dev/ which is
> similar to boost's shared_ptr. However, I've run into a problem. I'm
> willing to switch to the boost smart pointers, if they offer a
> solution
> to my problem. (But I'm guessing that a solution for one would work for
> the other.) Any help with either would be appreciated...
>
> I have an STL container of counted_ptr<A>'s. At some point I need to
> do a dynamic downcast of a counted_ptr<A> to a counted_ptr<B>. How do
> I do that?

Right now you don't. It has been on our chronic list of
missing features for a long time but no one has been
motivated enough to contibute a solution.

> The code is something like the following...
>
> class A
> {
> public:
> virtual int f() = 0;
> ...
> };
>
> class B : public A
> {
> public:
> virtual int f() = 0;
> virtual int g() { return -1; };
> };
>
> class C : public B
> {
> public:
> virtual int f() { return 1; };
> ...
> };
>
> class D : public B
> {
> public:
> virtual int f() { return 2; };
> ...
> };
>
> If I do...
>
> counted_ptr<A> cpA = input from somewhere
> A* pA = cpA.get();
> B* pB = dynamic_cast<A*>(pA);
> if(pB==NULL) throw("Illegal down cast!");
> counted_ptr<B> cpB = counted_ptr<B>(pB);
>
> ...then the counter will get messed up and my cpA could get deleted
> when the counter of cpB's gos to zero, even if the counter of cpA is
> >0.
>
> If I were using regular pointers (and non-STL contains), I could just
> do...
> A* pA = input from somewhere
> B* pB = dynamic_cast<A*>(pA);
> if(pB==NULL) throw("Illegal down cast!");
>
> If I were using counted_ptr's, but B wasn't virtual, then I could
> do...
>
> counted_ptr<A> cpA = input from somewhere
> A* pA = cpA.get();
> B* pB = dynamic_cast<A*>(pA);
> if(pB==NULL) throw("Illegal down cast!");
> B* pBn = new B(*pB);
> counted_ptr<B> cpB = counted_ptr<B>(pBn);
>
> ...but I can't allocate a new B object, since B's virtual. I suppose
> I could make a switch statement to test of each of C and D, although
> in my real code, that would result in a very large switch statement
> and make a pain for adding new classes. But I'm hoping you have a
> better suggestion (aside from avoiding dynamic downcasts).
>
> Thanks,
>
> Eric
>
>
>
>
> List-Unsubscribe: <mailto:boost-unsubscribe_at_[hidden]>
>
>
> Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/
>
>
>


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