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

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)

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.

Next Article: c++ 11 smart pointer.


Related Contents to follow