Caduchon
Caduchon

Reputation: 5201

How to dynamically cast a boost::scoped_ptr?

I'm surprised the compiler refuses to compile this kind of code :

class A { virtual ~A() {} };
class B : public A { virtual ~B() {} void foo() {} };
//...
boost::scoped_ptr<A> p1(new B);
boost::scoped_ptr<B> p2 = boost::dynamic_pointer_cast<B>(p1);
p2->foo();

Why this is not possible ? What is the best way to do that ?

I found this solution :

boost::scoped_ptr<A> p1(new B);
B* p2 = dynamic_cast<B*>(p1.get());
p2->foo();

Is there a way using intelligent pointers only ?

Note : I don't use C++11 for compatibility reason.

Upvotes: 0

Views: 404

Answers (1)

p1 owns the B object, and will delete it in its destructor. If you allowed the creation of a second smart pointer (p2) which was also going to delete the object in its destructor, you would have a problem.

Personally I would use a cast to a reference rather than a pointer, but apart from that, you have found the only solution.

Upvotes: 1

Related Questions