Smart Pointers

Create a class template SmartPointer that should contain a pointer to any object and delete that same object when the destructor of that class is called.
Does anyone knows how should i start and what should i add as a variable in this class? I tried to find something on the internet about smart pointers but i can not get it..

Well let’s see.

First you make a class template.
<begin class template>
<end class template>

Then, you make it contain a single variable; a pointer.
<begin class template>
  <pointer X>
<end class template>

Then, you define one method, the destructor.
<begin class template>
  <pointer X>
  <begin destructor>
  <end destructor>
<end class template>

Then, inside that destructor, delete the data of the pointer.
<begin class template>
  <pointer X>
  <begin destructor>
    <delete pointer X>
  <end destructor>
<end class template>



Edit: Also, you aren’t using a smart pointer, you’re making one. Also, smart pointers are like std::unique_ptr, std::shared_ptr... stuff like that. You should be adding a pointer of type T* where T is the template argument.
Last edited on

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Person
{
    string name;
    int age;
    public:
         Person(string nm, int a):name(nm), age(a){}
         void Display()
         {
              cout<<name<<"  "<<age;
         }
    // other member functions...
};
template<typename T> class TSP
{
	T* _ptr;
	public:
		TSP(T* ptr):_ptr(ptr){}
		~TSP()
		{delete _ptr;}
		T* operator->()
		{return _ptr;}
		T& operator*()
		{return *_ptr;}
};
void main()
{
	TSP<Person> obj(new Person("XYZ",26));
	obj->Display();
}
@akash16 ... generally when you are answering a question, try not to just give someone the answer in straight up exact code. It’s not... what’s that word... em. Constructive?
Topic archived. No new replies allowed.