65.9K
CodeProject is changing. Read more.
Home

Simple Smart Pointer Implemantation

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.59/5 (18 votes)

Sep 13, 2006

viewsIcon

27721

Implementaion of a simple smart pointer.

Introduction

Sometimes it is necessary to use something automatic instead of classical C++ pointers. For example you want that your pointer is automatically deleted. For this we need a class that automatize this things. Such class is called Smart Pointer.

template<class T>
class SmartPointer
{
public:
 SmartPointer(T* pointer)
  : mPointer(pointer)
 {}
 ~SmartPointer()
 {
  delete mPointer;
  release();
 }
 T* get()
 {
  return mPointer;
 }
 void release()
 {
  mPointer = NULL;
 }
 bool valid() const
 {
  return mPointer != NULL;
 }
 T* operator-> ()
 {
  return mPointer;
 }
 T& operator* ()
 {
  return *mPointer;
 }
private:
 T* mPointer;
 SmartPointer(SmartPointer&) {}
 SmartPointer& operator= (SmartPointer&) {}
};

We need a template class, because it should work with each type. The function get() returns the pointer, with the function valid() you can check whether the pointer has a valid value or not and the function release() sets the value of the pointer to NULL. We overload two operators: -> for the pointer and * for the value of the pointer. The most important thing of the smart pointer is this:

~SmartPointer()
{
  delete mPointer;
  release();
}

In the desctructor we automatically delete the pointer and then we set the value of the pointer to NULL.

This is an example how to use the smart pointer:

int main(int, char**)
{
 SmartPointer<int> pointer(new int); /* create a smart pointer with the type int */
 *pointer = 14; /* set the value to 14 */
 /* ... */
 return 0; 
} /* at the end of the scope the pointer will be automatically deletet */

It is very simple. I hope my article helped you.