26 Nov
2005
26 Nov
'05
7:21 p.m.
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());
Yes, it does. It will work even without a virtual destructor.
and later, delete(objectPtr).
This doesn't work.
Does any of the magic going on behind the scenes prevent shared_ptrs from being used like this?
Of course not. :-)