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

Code: Cpp

int main(){ MyClass *p (new MyClass); p->DoSomething();delete(p);}

We can write by trusting Smart Pointer or Auto Pointer, that p gets deleted on after it comes out of the scope :

Code: Cpp

int main(){ MyClass *p (new MyClass); p->DoSomething(); }

Though Smart Pointer is quite smart, but there is a below draw back with this:

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:

The code

Here class Pointer is a Real Pointer, where-as class Smart Pointer is a wrapper around Pointer.