smart pointer in c++ is an object which is used to wrap pointers of dynamically created objects and delete them automatically when they (dynamically created objects) go out of scope. memory leaks occurs when we call new without calling a corresponding delete in our c++ program. Managing new and corresponding delete in simple program is an easy task but when there are lots of classes and objects in large code base then it is very tough task to manage c++ memory or to avoid memory leaks. in this case c++ smart pointer comes to rescue memory leaks.

c++ smart pointer

Let Us see an example with memory leak

Example : 1

#include<iostream>
using namespace std;

class A {
   int a;
   public:
   A():a(5){}
};

int main()
{
  A *a_obj1 = new A();
  A *a_obj2 = new A();
  
  return 0;
}

The program example 1 has memory leak because we forgot to delete objects created at heap. in straight forward there is no delete corresponding to new. so if we would delete the dynamically created objects then there would be no memory leak in above program.

no  memory leak example 2 ( modified example 1)

#include<iostream>
using namespace std;

class A {
   int a;
   public:
   A():a(5){}
};

int main()
{
  A *a_obj1 = new A();
  A *a_obj2 = new A();
  
  delete a_obj1;
  delete a_obj2;
  return 0;
}

c++ smart pointer

can you write a generic smart pointer class that will work on above example?  Below code has a simple c++ smart pointer.

#include<iostream>
using namespace std;

template < typename T > class Ptr
{
private:
  T * ptr;
public:
Ptr (T * t):ptr (t)
  {
  };
  ~Ptr ()
  {
    delete ptr;
  }
  T & operator* ()
  {
    return *ptr;
  }
  T *operator-> ()
  {
    return ptr;
  }
};

class A
{
  int a;
public:
    A ():a (5)
  {
  }
};


int main ()
{
  Ptr <A> a_obj1( new A());
  Ptr<A> a_obj2( new A());
  // no need to delete a_obj1 and a_obj2
  // it will be deletd when out of scope
  return 0;
}

Next Article: c++ 11 smart pointer.

Ref:

https://en.wikipedia.org/wiki/Memory_leak



Related Contents to follow