-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHandle.cpp
More file actions
89 lines (77 loc) · 1.59 KB
/
Handle.cpp
File metadata and controls
89 lines (77 loc) · 1.59 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
#include <iostream>
#include <vector>
using namespace std;
class BaseItem{
public:
virtual BaseItem* clone()
{
return new BaseItem(*this);
}
virtual void sayHello()
{
cout<<"Hello, I am class BaseItem!"<<endl;
}
virtual ~BaseItem(){}
};
class ChildItem:public BaseItem{
public:
ChildItem* clone()
{
return new ChildItem(*this);
}
void sayHello(){
cout<<"Hello, I am class ChildItem!"<<endl;
}
};
template <typename T>
class Handle
{
public:
Handle():baseItem(NULL), refCount(new size_t(0)) {}
Handle(T& object):baseItem(object.clone()), refCount(new size_t(1)) {}
Handle(const Handle<T>& other):baseItem(other.baseItem), refCount(other.refCount)
{
++*other.refCount;
}
Handle& operator= (const Handle<T>& other)
{
++*other.refCount;
dec_count();
baseItem = other.baseItem;
refCount = other.refCount;
return *this;
}
const T* operator->() const {return baseItem;};
const T& operator*() const {return *baseItem;};
T* operator->() {return baseItem;};
T& operator*() {return *baseItem;};
virtual ~Handle(void)
{
dec_count();
}
private:
T *baseItem;
std::size_t* refCount;
void dec_count()
{
if (-- *refCount == 0 && baseItem != NULL)
{
delete baseItem;
delete refCount;
}
}
};
int main()
{
BaseItem item1;
ChildItem item2;
vector<Handle<BaseItem> > vec;
vec.push_back(Handle<BaseItem>(item1));
vec.push_back(Handle<BaseItem>(item2));
for (vector<Handle<BaseItem> >::iterator iter = vec.begin();
iter != vec.end(); iter++)
{
(*iter)->sayHello();
}
return 0;
}