Boost logo

Boost :

From: Kevlin Henney (Kevlin.Henney_at_[hidden])
Date: 2000-02-08 06:44:27


Miki Jovanovic wrote:
>OK, first I have to appologise for my code being in my own style...
>I have been working quite happily at work when an idea occured to
>me on how to make the shared_ptr polymorphic. For whatever reason
>I could not use the boost library, so I quickly jogged down this
>version of a polymorphic smart pointer.
>
>The problem I was trying to solve is: allow shared_ptr<DescendentClass>
>to be used anywhere shared_ptr<ParentClass> is expected.

I'm not sure that you are solving a problem: shared_ptr already supports
what you describe through its template member ctors and assignment
operators, ie

     shared_ptr<derived> p(new derived);
     shared_ptr<base> q = p;

is legal, and conforms to substitutability expectations set by built-in
pointers.

What neither built-in pointers nor shared_ptr support is the ability to
treat a reference to a pointer to derived as a reference to a pointer to
base, which is what you are proposing. The reason this undesirable is
because it is not type safe. Consider the consequences of allowing the
following code to compile:

     shared_ptr<derived> p;
     shared_ptr<base> q(new base);
     shared_ptr<base> & r = p;
     r = q;

Kevlin


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