-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_acquisition_is_initialisation_smart_pointer.cpp
121 lines (99 loc) · 2.03 KB
/
resource_acquisition_is_initialisation_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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#include <iostream>
using std::string, std::cout, std::cin, std::endl, std::to_string;
class Something
{
public:
string label;
Something()
{
cout << "Creation of Something..." << endl;
}
~Something()
{
cout << "Destruction of Something..." << endl;
}
};
class Acquisitor
{
protected:
Something * resource = NULL;
public:
Acquisitor(Something *something) : resource(something)
{
}
Acquisitor & operator=(Something *something)
{
resource = something;
return *this;
}
Something & operator*()
{
return *resource;
}
};
class SingleAcquisitor : public Acquisitor
{
public:
SingleAcquisitor() : Acquisitor(NULL)
{
}
SingleAcquisitor(Something *something) : Acquisitor(something)
{
}
~SingleAcquisitor()
{
delete resource;
}
};
class MultipleAcquisitor : public Acquisitor
{
public:
MultipleAcquisitor() : Acquisitor(NULL)
{
}
MultipleAcquisitor(Something *something) : Acquisitor(something)
{
}
~MultipleAcquisitor()
{
delete [] resource;
}
Something & operator[](int index)
{
return *(resource + index);
}
};
class SomeException
{
};
int main()
{
cout << endl << "Single object" << endl << endl;
try {
Something *temp = new Something;
SingleAcquisitor acquisitor = temp;
(*acquisitor).label = "Some thing";
cout << (*acquisitor).label << endl;
SomeException exception;
cout << "Throwing of SomeException." << endl;
throw exception;
} catch (SomeException e) {
cout << "Catching of SomeException." << endl;
}
cout << endl << "Array of objects" << endl << endl;
try {
MultipleAcquisitor acquisitor = new Something[4];
for (int i = 0; i < 4; i++) {
acquisitor[i].label = "Some thing no " + to_string(i);
}
for (int i = 0; i < 4; i++) {
cout << acquisitor[i].label << endl;
}
SomeException exception;
cout << "Throwing of SomeException." << endl;
throw exception;
} catch (SomeException e) {
cout << "Catching of SomeException." << endl;
}
cout << endl;
}