Skip to main content

Smart Pointer Basics in C++

    It is responsibility of the owner to free the memory which he is allocated dynamically. But the question is who actually owns the memory. Let us consider a function

char * allocate (int size)
{
      char * ptr = new char[size];
      return ptr;
}

here in this allocate function block of memory for characters is being allocated and the pointer to that memory location is returned. Now the question is the person who is calling this function if he doesnt store the pointer then what happens. If he stores and if he doesnt free then what happesns. In all these cases we can find memory leak.

To avoid these kind of situations in our code, its better to use the inbuilt functions provided by c++ standard library.

<memory> provides two smart pointers to help manage objects on the free store.

1. unique pointer
2. shared pointer

The most basic use of these smart pointer is to avoid memory leak.

Unique Pointer [unique_ptr]

std::unique_ptr is a smart pointer that retains ownership of an object through pointer and destroys that object when the unique_ptr goes out of scope.

Syntax :

std::unique_ptr <X> p1 (new X);   // p1 is a unique_ptr of type X

Once we declare this unique_ptr, no need to think of deallocating this object. The deallocation of this object happens automatically in one of these cases.
1. unique_ptr goes out of scope
2. when you assign unique_ptr object to other unique_ptr object via assignment operator or if you use reset.

Now again if we consider same example ,

char * allocate (int size)
{
      //char * ptr = new char[size];
      unique_ptr <char> ptr (new char[size]);
      return ptr;
}

Here in this function we are returning ptr, in this case the compiler creates a temp object and stores the value of ptr in temp object, if no one is catching that object the object will be destroyed and memory is freed. In case if we are not returning ptr here, the ptr goes out of scope when function ends and the object will be destroyed. Hence there is no possibility of memory leak here.

Shared Pointer

shared_ptr is similar to unique pointer, where are shared_ptr are copied rather than move. So the shared_ptrs share the ownership of an object , hence the object is destroyed when the last shared_ptr to that object is freed.

When we share an object, we need pointers to refer to the shared object, so the shared_ptr becomes the choice.


Most of the libraries in std, like vectors use these smart pointers for memory management, Hence there is very less or no chance of memory leak.

Unique_ptr example for creating shapes


#include <iostream>
#include <array>
#include <memory> //for unique_ptr class, for dyn alloc and dealloc of obj
#include <string>
using namespace std;


class Shape
{
public:
virtual void takeInput() = 0;
virtual void Draw() = 0;
};

class ShapeFactory;

vector <ShapeFactory *> g_factories; 

class ShapeFactory
{
protected:
ShapeFactory()
{
g_factories.push_back(this);
}
public:
virtual unique_ptr<Shape> Create() = 0;
virtual string getName() = 0;
};


int main()
{

for(int i=0;i<g_factories.size();i++)
{
cout<< i+1 <<":"<<g_factories[i]->getName()<<endl;

}

int choice;
cout<<"select a shape to be drawn";
cin >>choice;


unique_ptr <Shape> pShape = g_factories[choice-1]->Create();

pShape->takeInput();

pShape->Draw();

cout<<endl<<endl;

}



//implementation

class Circle:public Shape
{
int cx,cy, radius;
void takeInput()
{
cout<<"Enter cx, cy and radius";
cin>>cx>>cy>>radius;
}

void Draw()
{
cout <<"Circle :"<<cx<<" "<<cy<<" "<<radius<<" "<<endl;
}
};

class CircleFactory : public ShapeFactory
{
unique_ptr<Shape> Create()
{
unique_ptr <Shape> c (new Circle());
return c;
}

string getName()
{
return "Circle";
}
};
CircleFactory g_cf;

class Rectangle: public Shape //used to create objects
{
int left, top ,width, height;
void takeInput()
{
cout<<"Enter left top width and height";
cin >> left >> top >> width >>height;
}

void Draw()
{
cout <<"Rectangle :"<< left <<" " << top<<" " << width <<" "<<height<<" "<<endl;
}
};

class RectangleFactory : public ShapeFactory
{

unique_ptr<Shape> Create()
{
unique_ptr <Shape> r (new Rectangle());
return r;
}

string getName()
{
return "Rectangle";
}
};
RectangleFactory g_rf; 


class Triangle:public Shape
{
void takeInput()
{
cout<<"take in put trianle";
}

void Draw()
{
cout<<"trianle";
}
};

class TrianleFactory:public ShapeFactory
{
string getName(){
return "trianle";
}

unique_ptr<Shape> Create()
{
unique_ptr <Shape> t(new Triangle());
return t;
}
};


TrianleFactory g_tf;


I am not using any delete calls here even though i'm using new. But there cannot be any memory leak with this code. unique_ptr ensures that object is freed properly.



Comments

Popular posts from this blog

Basics of Programming : Variables

Variables Before going into definition of variable, let us consider any mathematical equation which we have studied in our schools. For example consider, 2x + 5y = 35 We do not have to know the use of this equation, but we just know that we can substitute some values for x and y which can satisfy the equation. For example (x,y) can take values (10, 3) or (5, 4). So we can say that x and y can hold some values or x and y can are placeholders for some data. In the same way we need something for holding data in computers. Those are called as variables. In other words we can also say that, variables are the name given for memory location. Since data are stored in some memory location, variables are the labels for those memory locations.

Linux Kernel - Introduction

Linux Torvalds developed the first version of Linux in 1991 as an operating system for computers powered by the intel microprocessor.   Started as a terminal emulator Linux evolved over a period. What is an operating system ? The operating system is considered as a part of the system responsible for basic use  and administration. This includes the kernel and device drivers, boot loaders, command  shell or other user interface and basic file and system utilities. The term system, in turn  refers to the operating system   and all the application running on top of it. The user interface is the outermost portion of the operating system, the kernel is the  innermost. The kernel sometimes referred as the supervisor, core or internals of the  operating system. Typical components if the kernel are interrupt handlers to service  interrupt requests, a scheduler to share the processor time among multiple processes,  a mem...

Basics of Programming : Data Types

We have seen that variables are placeholders for data. When we say data, it can be a integral numbers like 3,5 or it can be a real number like 2.6 , 1.8. In computer science, we define different types of data which we can store in memory location. A data type in a programming language is set of data with predefined values. Examples include, integers, floating point, characters, Strings etc. Even though ultimatly everything in memory stored in terms of zeros and ones, it is not practical  for us to code interms of zeros and ones. So to help users with programming compilers provide programmers the data types, which are in readable data which we use in day today transactions. The data types are categorized based on the representation in memory or the size it occupies in memory. For example, integer takes 4 bytes ( depends on the compiler, some may take 2 bytes), float takes 4 bytes, a character takes 1 byte. There are two types of data types. System define...