Smart pointer

Manish Goyal
@manish-r2Hoep • Oct 26, 2024

I hope most of you Guys are familiar with the concept of linked list,tress in c++
in all these each node point to next element ...now these nodes may not be in adjacent memory locations ....which in turn leads to complicated process
so in order to avoid this we use concept of smart pointers

Before beginning ..Have a look of this code

#include<iostream.h>
#include<conio.h>
int main()
{
const int max=5;
int a[]={10,20,30,40,50};
int *p;
p=arr;
for(int i=0;i<max;i++)
{
cout<<*p;
p++;
}
}

This is a simple method to use pointer to array.no problem for data structure like array ..but what for sophisticated data structures like linked list ,trees etc these plain pointers won't work..so we use smart pointers..as in linked list items may not be stored in adjacent memory locations,,so incrementing the pointers becomes complicated
this can solved by using this concept of 'smart pointers'
have a look of this class

class smartpointer
{
private:
int *p;
public:
int operator++()
{}
int operator*()
{}
};

the operators + & * are overloaded in this class to make it intelligent enough to handle such situations

Now there must be a question in your mind...
How and where to use????????😕😕

#include<iostream.h>
#include<conio.h>
class container
{
private:
structnode
{
int node;
node *link;
}*head,*current;
int current;
public:
container()
{
head=current=Null;
count=0;
}
void add(int n)
{
node *temp=new node;
temp->data=n;
temp->link=NULL;
if(head==NULL)
head=current=temp;
else
{
node *q;
q=HEAD;
while(q->link!=NULL)
{
q=q->link;
q->link=temp;
}
count++;
}
int getcount()
{
return count;
}
freind class smartpointer;
};

class smartpointer
{
private:
  container *p;
public:
smartpointer(conatiner *t)
{
cptr=t;
}
int operator *()
{
if(cptr->current=NULL)
return NULL;
else
{
int i=cptr->current->data;
return i;
}
}
 void operator++()
{
if(cptr->current!=NULL}
cptr->current=cptr->current->link;
}
};
void main()
{
container c;
c.add(12);
c.add(12);
c.add(13);
c.add(!4);
c.add(15);
smartpointer(&c);
for?(int i=0;i<c.getcount();i++)
{
cout<<*sptr;
sptr++;
}
}
int operator*()
{}
};

Here in smart pointer we have two overloaded operator functions
which can be used to handle such situations of non adjacent memory locations
The operator *() returns a integer in the current node;
the operator ++() advances the current pointer to point to next node in the linked list

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform