-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheg_smart_pointer.cpp
80 lines (64 loc) · 1.16 KB
/
eg_smart_pointer.cpp
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/* Smart pointer is a technique to use to reduce potential memory leaks caused by
* dynamic memory allocation.
* It can be thought as a wrapper class over normal pointers.
*/
#include <iostream>
using namespace std;
class Smartptr
{
int *ptr;
public:
Smartptr(int * p = NULL)
{
ptr = p;
cout << "Smartptr Constructor called"<< " Addresspassed = " << p << endl;
}
~Smartptr()
{
delete ptr;
cout << "I'm Smartptr Destructor" << endl;
}
/* Note: int& is the return type which is the c++ refernce type */
int& operator * ()
{
cout << " Overloaded part = " << ptr << "=" << *ptr << endl;
return *ptr;
}
};
/* generic smart pointer */
template <class T>
class SmartPtrTemplate
{
T* ptr;
public:
explicit SmartPtrTemplate(T* p = NULL)
{
ptr = p;
}
~SmartPtrTemplate()
{
delete (ptr);
}
T& operator * ()
{
return *ptr;
}
T* operator -> ()
{
return ptr;
}
};
int main()
{
int * ptr;
Smartptr pptr(new int);
SmartPtrTemplate<int> ppptr(new int());
ptr = new int;
*ptr = 11;
cout << *ptr << endl;
delete ptr;
*pptr = 22;
cout << *pptr << endl;
*ppptr = 33;
cout << *ppptr << endl;
}