forked from wadehuber/codeexamples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory.cpp
More file actions
133 lines (115 loc) · 3.36 KB
/
Copy pathmemory.cpp
File metadata and controls
133 lines (115 loc) · 3.36 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include <iostream>
using namespace std;
class MyMemoryClass {
private:
int *a;
int *b;
string name;
public:
// Constructor
MyMemoryClass(int size=5, const string & s="") : name(s){
cout << "CONSTRUCTOR " << name << endl;
a = new int;
*a = size;
b = new int[size];
for (int ii=0;ii<*a;ii++) {
b[ii] = ii+1;
}
}
// Copy Constructor
MyMemoryClass(const MyMemoryClass & original) {
name = original.name + "_copy";
cout << "COPY CONSTRUCTOR " << name << endl;
a = new int;
*a = *original.a;
b = new int[*a];
for (int ii=0;ii<*a;ii++) {
b[ii] = original.b[ii];
}
}
// Destructor
~MyMemoryClass() {
cout << "DESTRUCTOR " << name << endl;
delete a;
a = nullptr;
delete[] b; // Use delete[] when you use new with []
b = nullptr;
}
// Overloaded assignment operator
MyMemoryClass& operator=(const MyMemoryClass& otherObject) {
cout << "ASSIGNMENT OPERATOR " << name << endl;
if (this != &otherObject) {
// Allocate new memory for a & b
int * newA = nullptr;
int * newB = nullptr;
try {
newA = new int;
}
catch (...) {
if (newA != nullptr) {
delete newA;
}
}
try {
newB = new int[*(otherObject.a)];
}
catch (...) {
if (newA != nullptr) {
delete newA;
}
if (newB != nullptr) {
delete newB;
}
throw;
}
// Have new memory for a & b, now do the assignments
name = otherObject.name + "_assigned";
*newA = *(otherObject.a);
for (int ii=0;ii<*newA;ii++) {
newB[ii] = otherObject.b[ii];
}
delete a;
a = newA;
delete[]b;
b = newB;
}
return *this;
}
void print() {
cout << " MyMemoryClass " << name << " {" << a << "} {" << b << "} "
<< *a << ": " ;
for(int ii=0;ii<*a;ii++) {
cout << b[ii] << " ";
}
cout << endl;
}
};
void func(MyMemoryClass x) {
cout << "FUNC: ";
x.print();
}
int main() {
MyMemoryClass c1(10, "c1"); // value semantics
MyMemoryClass * c2;
c2 = new MyMemoryClass(5, "c2"); // reference semantics
MyMemoryClass c3(14, "c3");
//MyMemoryClass c3 = c1;
cout << "C1: " << endl;
c1.print();
cout << "C2: " << endl;
c2->print();
cout << "C3: " << endl;
c3.print();
cout << endl;
cout << "C3 = C1: " << endl;
c3 = c1;
c1.print();
c3.print();
cout << endl << "Calling functions: " << endl;
func(c1);
func(c3);
cout << endl;
delete(c2);
cout << endl << "End of program" << endl;
return 0;
}