-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSmartPtr.h
More file actions
100 lines (81 loc) · 2.18 KB
/
SmartPtr.h
File metadata and controls
100 lines (81 loc) · 2.18 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/************************************************************************************************************************************************************************************************************
*FILE: SmartPtr..h
*
*DESCRIPTION - Takes care of Managing the references made by objects
*
*
*AUTHOR : RAMESH KUMAR K
*
*Date: OCT 2016
**************************************************************************************************************************************************************************************************************/
#pragma once
template <typename T>
inline void SafeRelease(T **p)
{
if (*p)
{
(*p)->Release();
*p = NULL;
}
}
/**
* A reference counting-managed pointer for classes derived from RefrenceCounter which can
* be used as C pointer
*/
template<class T>
class SmartPtr
{
public:
//Construct using a C pointer
//e.g. SmartPtr<T> x = new T();
SmartPtr(T* ptr = NULL) : mPtr(ptr)
{
if (ptr != NULL) { ptr->AddRef(); }
}
//Copy constructor
SmartPtr(const SmartPtr &ptr)
: mPtr(ptr.mPtr)
{
if (mPtr != NULL) { mPtr->AddRef(); }
}
~SmartPtr()
{
if (mPtr != NULL) { mPtr->Release(); }
}
//Assign a pointer
//e.g. x = new T();
SmartPtr &operator=(T* ptr)
{
if (ptr != NULL)
{
ptr->AddRef();
}
if (mPtr != NULL)
{
mPtr->Release();
}
mPtr = ptr;
return (*this);
}
//Assign another SmartPtr
SmartPtr &operator=(const SmartPtr &ptr)
{
return (*this) = ptr.mPtr;
}
//Retrieve actual pointer
T* get() const
{
return mPtr;
}
//Some overloaded operators to facilitate dealing with an SmartPtr as a convetional C pointer.
//Without these operators, one can still use the less transparent get() method to access the pointer.
T* operator->() const { return mPtr; } //x->member
T &operator*() const { return *mPtr; } //*x, (*x).member
operator T*() const { return mPtr; } //T* y = x;
operator bool() const { return mPtr != NULL; } //if(x) {/*x is not NULL*/}
bool operator==(const SmartPtr &ptr) { return mPtr == ptr.mPtr; }
bool operator==(const T *ptr) { return mPtr == ptr; }
//T* operator new(const T()) { (new T())->template DetachObject<T>(); } // needed to be tested
private:
T *mPtr; //Actual pointer
};