Boost logo

Boost Users :

From: Jonathan Biggar (jon_at_[hidden])
Date: 2005-11-26 14:18:09


Merrill Cornish wrote:
> With an ordinary C++ pointer, if I have a BaseClass and a DerivedClass derived
> from BaseClass, then I can do
>
> BaseClass* objectPtr;
> objectPtr = new DerivedClass();
>
> Later, if BaseClass has a virtual destructor, I can call delete(objectPtr) and the
> DerivedClass destructor will be called.
>
> Now, does this work with shared_ptr?
>
> shared_ptr<BaseClass> objectPtr;
> objectPtr = shared_ptr<DerivedClass>(new DerivedClass());
>
> and later, delete(objectPtr).

No, you shouldn't call delete directly. It's done for you automatically
when the last shared_ptr that points to your object is destroyed.

> Does any of the magic going on behind the scenes prevent shared_ptrs from
> being used like this?

shared_ptr would be close to useless if it didn't. In fact, shared
pointer does *more* to remember the dynamic type than ordinary pointers.
  Forex, you can do this:

     {
        shared_ptr<void> voidPtr;
        voidPtr = shared_ptr<Object(new Object());
      } # here your object is destroyed with the correct destructor

-- 
Jonathan Biggar
jon_at_[hidden]

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