Skip to content

Instantly share code, notes, and snippets.

@twentyse7en
Last active December 7, 2020 14:08
Show Gist options
  • Save twentyse7en/f9ad33b1110595425cdc87505ae8b844 to your computer and use it in GitHub Desktop.
Save twentyse7en/f9ad33b1110595425cdc87505ae8b844 to your computer and use it in GitHub Desktop.
Smart Pointers

Smart Pointer

Why use Pointers ?

For accessing the elements created inside the Heap we have to use pointer

Is using Pointers safe ?

We have to manully deallocate the memory after the use, or it will waste the space inside the Heap, may eventually crash the program in worst case

#include <iostream> 
using namespace std; 
 
class Rectangle { 
private: 
   int length; 
   int breadth; 
}; 
 
void fun() 
{ 
   // By taking a pointer p and 
   // dynamically creating object 
   // of class rectangle 
   Rectangle* p = new Rectangle(); 
} 
 
int main() 
{ 
   // Infinite Loop 
   while (1) { 
       fun(); 
   } 
} 

The memory is never deallocated, It causes huge problem

Is there any Solution ?

In other languages there is garbage collection that handles the deallocation for you. Don't get disappointed in c++ there is `smart pointers` to help you with this problem.

Types of smart pointers

Unique Pointers

As the name suggest at a time only one pointer points to a memory location. c++ don't allow copying the unique pointer. This is useful because, the memory location automatically gets deleted after the scope. If we have multiple copies, they might point to already deleted location, things get messy real fast.

#include <iostream>
#include <memory>       //----> import

using namespace std;


class Rectangle
{
   private:
       int length, width;

   public:
       Rectangle(int l, int w)
           : length(l), width(w)
           {}

       void Area()
       {
           cout << "AREA: " << length * width << endl;
       }

       ~Rectangle()
       {
           cout << "Object got deleted" << endl;
       }
};

int main()
{
   // ========= NOTE ===============
   //  you can't do assignment
   // R1 = new Rectangle(10, 20);
   // this is not allowed
   
   unique_ptr<Rectangle> R1(new Rectangle(10, 2));

   R1->Area();
}

Shared Pointers

When you have to keep the multiple copies of a pointer, you can keep shared pointer. Here reference counter keep track of the active pointers. If the counter is 0, then the memory get deallocated.

int main()
{
   shared_ptr<Rectangle> R2;
   {
       shared_ptr<Rectangle> R1 = make_shared<Rectangle>(10, 20);
       R1->Area();
       R2 = R1;
       cout << "Entity is still alive" << endl;
   }


}

Weak pointers

Here the ref count is not incremented.

int main()
{
   weak_ptr<Rectangle> R2;
   {
       shared_ptr<Rectangle> R1 = make_shared<Rectangle>(10, 20);
       R1->Area();
       R2 = R1;
   }
   cout << "Entity is still not alive" << endl;


}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment