forked from Hawstein/cracking-the-coding-interview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
13.9.cpp
65 lines (56 loc) · 1.29 KB
/
13.9.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
#include <iostream>
#include <cstdlib>
using namespace std;
template <typename T>
class SmartPointer{
public:
SmartPointer(T* ptr){
ref = ptr;
ref_count = (unsigned*)malloc(sizeof(unsigned));
*ref_count = 1;
}
SmartPointer(SmartPointer<T> &sptr){
ref = sptr.ref;
ref_count = sptr.ref_count;
++*ref_count;
}
SmartPointer<T>& operator=(SmartPointer<T> &sptr){
if (this != &sptr) {
if (--*ref_count == 0){
clear();
cout<<"operator= clear"<<endl;
}
ref = sptr.ref;
ref_count = sptr.ref_count;
++*ref_count;
}
return *this;
}
~SmartPointer(){
if (--*ref_count == 0){
clear();
cout<<"destructor clear"<<endl;
}
}
T getValue() { return *ref; }
private:
void clear(){
delete ref;
free(ref_count);
ref = NULL; // 避免它成为迷途指针
ref_count = NULL;
}
protected:
T *ref;
unsigned *ref_count;
};
int main(){
int *ip1 = new int();
*ip1 = 11111;
int *ip2 = new int();
*ip2 = 22222;
SmartPointer<int> sp1(ip1), sp2(ip2);
SmartPointer<int> spa = sp1;
sp2 = spa;
return 0;
}