I seriously looked at shared_ptr after your original inquiry, because I was unsure of some details. I thought its implementation targeted memory efficiency and was kind-of rigid, but it sacrifices memory efficiency for versatility.
The basic implementation of (reference counting garbage collecting) smart pointer keeps pointer to proxy object. In the proxy, it maintains the reference count and holds the value of the actual raw pointer. The proxy is dynamically allocated and is shared by (hopefully) all smart pointers that reference the same managed object.
The management policy concerns primarily the copy constructor, copy assignment operator, and destructor. When you create another copy of the smart pointer (with constructor or assignment), you increment the count inside the proxy. When you discard one of the copies (with destructor or overwriting with assignment), you decrement the reference count. And of course, the actual pointed object is destroyed using the raw pointer when the reference count reaches zero. After that the proxy is also destroyed.
With this strategy, you can not point to (different) sub-objects (base classes, fields, fields of fields, etc.), because all smart pointers that manage the same object share the count and the raw pointer. Second, the proxy indirection slows down the access a bit.
The alternative is to add another raw pointer as field stored directly in the smart pointer. It points to the sub-object (or more generally any controlling object) that is accessed with this smart pointer. The additional field is outside the proxy and is therefore not shared, which means that its value is independent, but it doubles the memory used for individual smart pointers.
To support weak pointers, the proxy maintains one additional reference count that impacts only the lifetime of the proxy itself. But this is not important.
What I am saying is this: you can point the smart pointer to virtually anything, and still manage the lifetime of one specific object that you wish. You can even point the smart pointers to static variables, and still manage some dynamically allocated memory through them. And you certainly can cast to your heart's content, as long as the casts are valid.
maalathi wrote: |
---|
then is it not possible to typecast the derived object to baseclass object & then delete it ? |
No. It may work in practice with actual compilers, but the standard does not guarantee that performing invalid downcast and then reversing it with upcast recovers the original pointer. But it will probably work in practice if you test it.
Regards