Boost logo

Boost Users :

Subject: [Boost-users] Covariant return type, method hiding, and shared_ptr advice
From: Dominique Devienne (ddevienne_at_[hidden])
Date: 2009-04-15 13:09:25


(follow up to the "How to obtain shared_ptr<Derived> from
shared_ptr<Base>?" post)

class Ident { ... };
class Object {
   Ident* ident() { return ident_.get(); }
   const Ident* ident() const { return ident_.get(); }
   shared_ptr<Ident> ident_ptr() { return ident_; }
private:
   shared_ptr<Ident> ident_;
};

class VehicleIdent : public Ident { /* Vehicle-specific ident members */ }
class Vehicle : public Object {
    // covariant return type
   VehicleIdent* ident() { return
polymorphic_downcast<VehicleIdent*>(Object::ident()); }
   const VehicleIdent* ident() const { /* same as above */ }
};

In the class hierarchy above, I return both raw and shared_ptr of an
object's identity, something that opens up the possibility for bugs
were the raw pointers is deleted or stuffed into another "unrelated"
smart pointers.

But on the other hand, when I'm dealing with a Vehicle (corrected
spelling ;) instead of an Object, I'd like to get it's ident with the
proper type (VehicleIdent), to access the vehicule-specific identity
naturally (those methods are not shown here).

So I used covariant return type, which AFAIK works only for raw
pointers. If I were to remove the raw pointer accessors, I'd have to
do either:

class Object {
   shared_ptr<Ident> ident() { return ident_; }
};
class Vehicle : public Object {
   shared_ptr<VehicleIdent> vehicule_ident() { ... }
};

i.e. have a new method each time, which is less uniform, or:

class Object {
   shared_ptr<Ident> ident() { return ident_; }
};
class Vehicle : public Object {
   shared_ptr<VehicleIdent> ident() { ... }
};

which hides the base ident() in the derive classes.

What is the best alternative? Or is there a better way to deal with
this? Thanks, --DD

PS: is returning a const shared_ptr<T>& is better/worse than a copy?


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