Mr. Lidström and I had an argument :)
Mr. Lidström's claim is that a construct shared_ptr<Base> p(new Derived);
doesn't require Base to have a virtual destructor:
Armen Tsirunyan: "Really? Will the shared_ptr clean up correctly? Could you please in this case demonstrate how that effect could be implemented?"
Daniel Lidström: "The shared_ptr uses its own destructor to delete the Concrete instance. This is known as RAII within the C++ community. My advice is that you learn all you can about RAII. It will make your C++ coding so much easier when you use RAII in all situations."
Armen Tsirunyan: "I know about RAII, and I also know that eventually the shared_ptr destructor may delete the stored px when pn reaches 0. But if px had static type pointer to
Base
and dynamic type pointer toDerived
, then unlessBase
has a virtual destructor, this will result in undefined behavior. Correct me if I am wrong."Daniel Lidström: "The shared_ptr knows the static type is Concrete. It knows this since I passed it in its constructor! Seems a bit like magic, but I can assure you it is by design and extremely nice."
So, judge us. How is it possible (if it is) to implement shared_ptr without requiring polymorphic classes to have virtual destructor?
shared_ptr<void> p(new Derived)
will also destroy theDerived
object by it's destructor, regardless if it isvirtual
or not. – Walkthroughshared_ptr<T>( (T*)new U() )
wherestruct U:T
won't do the right thing (and this can be done indirectly easily, such as a function that takes aT*
and is passed aU*
) – CatkinT
does not have a virtual destructor, or isvoid
. – Telegonusstd::shared_ptr
), but it draws liberally from Boost. Thus, sellibitze's answer says:Boost does and the upcoming standard also requires this behaviour.
– Beera