Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2002-01-18 08:40:21


From: "Tom Becker" <voidampersand_at_[hidden]>
> Going back to your example of the unsafe code, correct me if I'm
> wrong, but I think this boils it down to the minimum:

No, your example is quite different.

> struct Base { Base(); ~Base(); };
> struct Derived : Base { Derived(); ~Derived(); };
>
> void unsafe()
> {
> shared_ptr<Base> b(new Derived);

The expression "delete get()" invokes undefined behavior, therefore the code
is ill-formed.

> b.reset(); // equivalent to delete (Base*)(new Derived)!!
> };
>
> That's because, as long as shared_ptr<Base> allows construction from
> a Derived*, it doesn't matter where the Derived* is obtained from.
> Unfortunately, that means that tricks such as auto_ptr_ref can't save
> us here.
>
> How about adding an additional constructor:
>
> template<typename Y>
> explicit shared_ptr(Y* p);

Doesn't help.

Base * p = new Derived;
shared_ptr<Base> b(p);

The original example was:

shared_ptr<Derived> d(new Derived);
shared_ptr<Base> b(d);
d.reset();
b.reset();

Which line invokes the undefined behavior? My answer is "none of them" and
therefore I have implemented a version of shared_ptr that handles the
example fine.

--
Peter Dimov
Multi Media Ltd.

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