≡ Menu

How to use Smart Pointers in C++ with Example Code

In C and C++ programming, pointers are very powerful.

As we explained in C pointers example article, pointers are variables that hold address of another variable so that we can do various operations on that variable.

Sometimes a programmer can’t imagine writing a code without using pointers, whether it is a simple binary search tree program, or a complex enterprise application.

But, pointers are hard to manage, master, and they can cause many problems if not handled properly.

For example, when not properly used, it can cause core dumps, dangling pointer, null pointer exception, memory leaks, etc.

Consider the following code snippet. What happens when we get an exception in the Study() method?

Geek* geek=new Geek();
Geek->Study();
delete geek;  
// If study method raises an exception, who would do the above memory clean-up?

The solution to the above problem is Smart Pointers.

Smart pointers automatically handle many of these problems. They are basically an object which behave like pointers i.e. wrap a bare pointer but provides extra functionality. So we should use these in place of bare pointers.

Now, let us understand the basics of how smart pointers work. Please note that this is just one of the various methods used for creating smart pointers.

The basic idea is to create a wrapper for a bare pointer, and overload few operators that will be used, * , -> the automatic clean-up part will be handled by the destructor of the class.

#include<iostream>
class Ptr
{
  int *ptr;
  public:
    explicit  Ptr(int *p = NULL) { ptr = p; }

  ~Ptr() { delete(ptr); }
  int &operator *() {  return *ptr; }

};
int main()
{
  Ptr ptr(new int());
  *ptr = 4;
  cout << *ptr;
  return 0;
}

In this code we don’t need to free the memory after using the dynamically allocated variable.

This shows the basic idea behind the implementation. You can easily make it generic by using template library.

Another idea is based on reference counting that is used in shared pointer, it is being used to share the ownership of object.

Every time a new pointer points to this object reference object is increased by one, and when the pointer release the ownership of object, object is automatically destroyed when the last pointer pointing to it is release the ownership.

Code Example:

#include<iostream>
class Ptr
{
  int *ptr;
  int count;
  public:
    explicit  Ptr(int *p = NULL)
    { ptr = p; 
      Count++;
    }

  ~Ptr() {
    count--;
    If(count==0) 
      delete(ptr); 
  }

  int &operator *() {  return *ptr; }

};

int main()
{
  Ptr ptr(new int());
  *ptr = 4;
  cout << *ptr;
  return 0;
}

This above code shows the basic idea on how to use reference counting for smart pointer implementation.

You can modify the above code to make it generic and write your own smart pointer and use it.

There are also few open source libraries available for smart pointers including the boost pointer library.

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

{ 3 comments… add one }

  • SR-71 February 14, 2015, 5:45 pm

    Other than Boost, could be worth to mention that the C++ standard encompasses smart pointers templates, in two flavours, shared and unique pointers. For a comprehensive explanation see the last Scott Meyers’s book.

  • James Ting February 17, 2015, 7:22 pm

    Is there some try catch mechanism so that pointer memory can be cleaned up?

  • Andrei March 3, 2015, 11:38 am

    In the second example there is a typo. “Count” should be changed to “count” in the constructor.

Leave a Comment