How to obtain shared_ptr<Derived> from shared_ptr<Base>?
I have a class diagram with the following base classes:
class Object;
class Ident { ...
private: ...
friend class Object;
void set_object(Object* obj) { object_ = obj; }
private: ...
Object* object_;
};
class Object { ...
public:
Ident* ident() { return ident_.get(); }
const Ident* ident() const { return ident_.get(); }
shared_ptr<Ident> ident_ptr() { return ident_; }
protected:
Object(shared_ptr<Ident> ident) : ident_(ident) {
ident_->set_object(this); }
virtual ~Object() { ident_->set_object(0); }
private:
shared_ptr<Ident> ident_;
};
An Object in memory always has an Ident, which it shares with client
code, but the Ident of an Object can be loaded before the object
itself, and will also remain after the Object is gone, as long as
client code references it. Ident has a "back" pointer to its Object,
which is maintained by Object directly via friendship. (yes, the
design is tightly coupled). In effect Ident is almost like a "weak"
proxy to its Object.
Then there are derived class pairs from Ident+Object:
class VehiculeIdent : public Ident { /* Vehicule-specific ident members */ }
class Vehicule : public Object {
protected:
Vehicule() : Object(shared_ptr<VehiculeIdent>(new VehiculeIdent)) {}
public: // covariant return type
VehiculeIdent* ident() { return
polymorphic_downcast
Dominique Devienne wrote:
So long story short, is there a clean way to obtain a shared_ptr<VehiculeIdent> from a shared_ptr<Ident> which one "knows" is a VehiculeIdent, to avoid my as_shared_ptr hack above?
Use dynamic_pointer_cast: http://www.boost.org/doc/libs/1_38_0/libs/smart_ptr/shared_ptr.htm#functions
AMDG Dominique Devienne wrote:
So long story short, is there a clean way to obtain a shared_ptr<VehiculeIdent> from a shared_ptr<Ident> which one "knows" is a VehiculeIdent, to avoid my as_shared_ptr hack above?
I think you want static_pointer_cast. http://www.boost.org/libs/smart_ptr/shared_ptr.htm#static_pointer_cast In Christ, Steven Watanabe
On Wed, Apr 15, 2009 at 9:59 AM, Steven Watanabe
Dominique Devienne wrote:
So long story short, is there a clean way to obtain a shared_ptr<VehiculeIdent> from a shared_ptr<Ident> which one "knows" is a VehiculeIdent, to avoid my as_shared_ptr hack above?
I think you want static_pointer_cast. http://www.boost.org/libs/smart_ptr/shared_ptr.htm#static_pointer_cast
Thank you both Nat and Steven. I was unaware that shared_ptr had equivalents to the standard casts. Makes perfect sense now. Thanks again, --DD
participants (3)
-
Dominique Devienne
-
Nat Goodspeed
-
Steven Watanabe