Monday, August 07, 2006

Smart pointers

Smart pointers are template classes that store pointers to classes. Smart pointers provide same functionality of built-in pointers with some more smart operations.

First let us look at drawbacks of ordinary pointers:

  1. No automatic deletion.

  2. More than one reference.

Class1* x = new Class1() ;

Class1* y = x ;

Now who will delete Class1()? x or y .

  1. No garbage collection.

  2. Assignment operator not suitable.


template <>
class SmartPointer

{
public:
explicit SmartPointer(T* pointer) : ptr(pointer);
SmartPtr& operator=(const SmartPtr&amp;amp; other);
~SmartPtr();
T& operator*() const
{
return *ptr;
}
T* operator->() const
{
return ptr;
}
private:
T* ptr;
};


Smart pointers do the same operations as ordinary pointers as:

  • T& operator*() const

  • T* operator->() const

While other smart capabilities can be implemented as:

  • Auto initialize pointer to null.

  • Destructor frees allocated memory.

  • Smart assignment

template

SmartPointer & SmartPointer ::operator=( SmartPointer & sptr)

{

if (this != &rhs) {
delete ptr;
ptr = sptr.ptr;
sptr.ptr = NULL;
}
return *this;
}
return *this;
}

Now we gave a pointer to only the newly assigned pointer and deleted the other one!
Other ideas may be implemented as needed as allocating new data and copying it!!

  • Garbage collection(c++ doesn’t have garbage collection so smart pointers can be used for that purpose but how??).

Smart pointers in STL

  • auto_ptr is an example of smart pointers.

No comments: