|
Boost Users : |
From: Peter Dimov (pdimov_at_[hidden])
Date: 2002-08-26 10:33:48
From: "Olaf Petzold" <yg-boost-users_at_[hidden]>
> Thank you,
>
> >> struct C : public BaseC {
> >> C() : b( new B("C::b") ) { }
> >> void set(const boost::shared_ptr<A>& ptr) {
> >> b.swap( boost::shared_static_cast<B>( ptr ) ); // L21
> >> }
> >> void print() { std::cout << b->name << std::endl; }
> >> boost::shared_ptr<B> b;
> >> };
> >
> > Why not simply
> >
> > b = boost::shared_static_cast<B>( ptr );
> >
> > or
> >
> >
> > b = boost::shared_polymorphic_cast<B>( ptr );
>
> I want to swap the pointers inside for further use (for saving the old ptr
> contents and restoring for circumstances - clone() may be one way before
> set() it but has overhead).
You can't swap() two pointers (objects, in general) of different types, and
you can't swap() with a temporary (which is what the cast returns.)
One possible way is to change set() to return the old value:
shared_ptr<A> set(shared_ptr<A> const & p)
{
shared_ptr<A> tmp(b);
b = boost::shared_polymorphic_cast<B>(p);
return tmp;
}
You can keep the old interface (minus the "const" on the parameter) if you
want, but the swapping needs to be done "by hand":
void set(shared_ptr<A> & p)
{
shared_ptr<A> tmp(b);
b = boost::shared_polymorphic_cast<B>(p);
p = tmp;
}
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