What are smart Pointers in C++

In this short tutorial, we are going to discuss the smart pointers in C++. Basically, we are going to cover the topics what do smart pointers mean? Which are smart pointers available in C++? What is the purpose of the smart pointers?

Smart pointers in C++ are referred to as abstract data type which can simulate the pointer at the same time providing some of the added features. The added features can be automatic memory management and bounds checking. Such features are intended to reduce bugs caused by the misuse of pointers but it also ensures that the efficiency is maintained. Smart pointers generally held the track of the memory which they point and also used to manage other resources, for example, network connections and file handles.

Some of the times it is possible that after the use of the object it remains in the memory. So for some time, it consumes memory in the program because the object is no longer usable, smart pointers ensure that the object is deleted if it is no longer in use, that’s the main purpose of the smart pointers. The following list consists of some really special templates which are used as the smart pointers in C++.

Some special template which can be used as smart pointers.

  • unique_ptr
  • shared_ptr
  • weak_ptr
  • auto_ptr


std::unique_ptr<int> s1(new int(8));
std::unique_ptr<int> s2 = s1; 
std::unique_ptr<int> s3 = std::move(s1);

shared_ptr and weak_ptr

std::shared_ptr<int> s0(new int(8));  
std::shared_ptr<int[]> s1(new int[8]);  
std::shared_ptr<int[]> s2 = s1;  


Leave a Reply

Your email address will not be published. Required fields are marked *