Smart pointer with Reference Counting
This article talks a little bit about Smart Pointer conepts and then move on to Reference Counting. Then there is a smaple code to implement the same.
Smart pointer or auto-pointer is a simple wrapper around a regular pointer, provides all meaningful operations to it's embedded piointer (derefencing and indirection).
It's smartness lies in it's destructor which takes care of deleting it's embedded pointer and makes user not to worry from freeing his/her dynamically allocated memory.
The fundamental logic behind designing Smart Pointer is that the Stack is safer than Heap. Variables on the Stack are automatically destructed when they go out of scope. Whereas Variables on Heap are freed only by an explicit call to Delete.
So, the trick is to represent Heap based object, accessed through a dumb pointer by a stack based object and when this stack based object goes out of scope, it's Destructor is called, which in turn takes care of freeing the memory associated with the dumb pointer.
For Example here instead of writing
We can write by trusting Smart Pointer or Auto Pointer, that p gets deleted on after it comes out of the scope :
Though Smart Pointer is quite smart, but there is a below draw back with this:
See the below code
i.e. When we assign pointer p to q as in the above code and then delete pointer p, it simply deletes the object pointed by pointer "p", irrespective of tehre is another pointer "q" refrencing to it and then currupts the heap.
There are set of solutions to this problem. But we can solve this in a simple way by providing refrence counting facility to the embedded pointer.
Reference Counting does maintain a count of all the pointers that are referencing to the object and deletes the object only when this Reference Count becomes Zero or when the last object which is using this pointer gets destroyed.
Also you can use reference counting in any class that manages a shared resource, and not just for smart pointers or auto pointers.
Logic behind Refrence Counting implementation is as below:
1. When the object that is being managed is created, its reference count
is set to one.
2. When the managing object - the smart pointer - is copied or assigned,
the reference count is incremented.
3. When a smart pointer is destructed, as when a member variable's owning
object is destructed, or a value goes out of scope, or an allocated
smart pointer is deleted, the reference count is decremented.
4. Once when the refCount becomes zero, then the pointer gets deleted.
This is also called as Shared Ownership Pattern.
Here is a sample code which implements Smart Pointer with Reference Conting:
Here class Pointer is a Real Pointer, where-as class Smart Pointer is a wrapper around Pointer.
Re: Smart pointer with Reference Counting
Article of the month competition nomination started here
|All times are GMT +5.5. The time now is 21:47.|