Boost logo

Boost :

From: Luigi Ballabio (ballabio_at_[hidden])
Date: 2002-01-14 15:21:50


> > At 08:56 AM 1/14/02 -0500, you wrote:
>> >struct Base { Base(); ~Base(); };
>> >struct Derived : Base { Derived(); ~Derived(); };
>> >
>> >void unsafe()
>> >{
>> > shared_ptr<Derived> d(new Derived);
>> > shared_ptr<Base> b(d);
>> > d.reset();
>> > b.reset(); // equivalent to delete (Base*)(new Derived)!!
>> >};
>> >
>> >Isn't shared_ptr just screaming for the application of John Maddock's new
>> >is_polymorphic<> trait?
>>
>> Maybe I'm just about to embarass myself, but isn't Base just screaming for
>> having a virtual destructor instead, if you want to use it this way?
>
>The point is that non-polymorphic public bases are an important and useful
>construct, and safe as long as you don't explicitly delete a derived through
>the base pointer.

I wholeheartedly agree, and my point was that they should be used
exactly as such---as non-polymorphic. Maybe I'm just being dense (no
irony. Maybe I'm just being dense. Really.) but what would be the
reason for upcasting a derived class to its base, if dynamic dispatch
is not to be used? If there are no virtual function in Base, casting
Derived* to Base* or shared_ptr<Derived> to shared_ptr<Base> is
surely a lot less nasty than slicing Derived to Base when passing by
value (since no harm is done to the actual object if one doesn't
delete the Base*). However, it looks suspicious to me, since deleting
the object through the Base* is not the only harm one can do. What if
the base class has a setter method, and the derived class overrides
it to call the base implementation _and_ update some additional state
specific to Derived? If one calls such method through the
non-polymorphic Base* or shared_ptr<Base>, isn't the Base
implementation called, thus leaving the additional Derived state
invalid? In this case, I'd rather have a visible leak which signals
me that something is fishy with the cast I let slip in, rather than
having code that seems to work fine but with a subtle bug which might
change my results without me noticing. But that's just me (and a
rather humble me, too).

Bye,
        Luigi

-- 

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