-
Notifications
You must be signed in to change notification settings - Fork 158
Expand file tree
/
Copy pathSmart pointer.cpp
More file actions
51 lines (40 loc) · 815 Bytes
/
Smart pointer.cpp
File metadata and controls
51 lines (40 loc) · 815 Bytes
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
/*
implement smart pointer in C++
*/
template <class T>
class SmartP {
public:
SmartP(const SmartP<T>& p) { incRef(p); }
SmartP(T* p) { assign(p); }
~SmartP() { decRef(); }
SmartP<T>& operator = (const SmartP<T>& p) {
if (this != &p)
{
decRef();
incRef(p);
}
return *this;
}
T* operator ->() const { return val; }
T& operator *() const { return *val; }
private:
void decRef() s{
(*ref)--;
if (0 == *ref)
{
delete val;
delete ref;
}
}
void incRef(const SmartP<T>& ptr) {
ref = ptr.ref;
val = ptr.val;
(*ref)++;
}
void assign(T* p) {
val = p;
ref = new int(1);
}
T* val;
int* ref;
};