forked from wadehuber/codeexamples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruleof5.cpp
More file actions
81 lines (66 loc) · 1.88 KB
/
Copy pathruleof5.cpp
File metadata and controls
81 lines (66 loc) · 1.88 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
#include<iostream>
#include<vector>
using namespace std;
class RuleOf5 {
private:
int x;
public:
explicit RuleOf5(int n=0) : x(n) { cout << "Constructor x=" << x << endl; }
~RuleOf5() { cout << "Destructor x=" << x << endl; }
// Copy constructor
RuleOf5(const RuleOf5 & that) {
x = that.x + 10;
cout << "Copy Constructor " << x << endl;
}
// Copy assignment - overload operator=
RuleOf5& operator=(const RuleOf5 & that) {
if (this != &that) {
x = that.x + 100;
cout << "Copy Assignment (overloaded operator=) " << x << endl;
}
return *this;
}
// Move constructor
RuleOf5(const RuleOf5 && that) {
x = that.x + 10;
cout << "Move Constructor " << x << endl;
}
// Move assignment - overload operator=
RuleOf5& operator=(const RuleOf5&& that) {
if (this != &that) {
x = that.x + 10000;
cout << "Move Assignment (overloaded operator=) " << x << endl;
}
return *this;
}
};
RuleOf5 makeRuleOf5() {
RuleOf5 varLocal(2);
return varLocal;
}
int main() {
// Constructor
RuleOf5 varOriginal(1);
cout << endl;
// Copy constructor
RuleOf5 varCopyConstructor = varOriginal;
cout << endl;
// Copy assignment
RuleOf5 varCopyAssignment;
varCopyAssignment = varOriginal;
cout << endl;
// Move assignment
RuleOf5 varMoveAssignment;
varMoveAssignment = makeRuleOf5();
cout << endl;
// Move constructor
vector<RuleOf5> v;
v.push_back(RuleOf5(3));
cout << endl;
// std::move
RuleOf5 varStdMove;
varStdMove = std::move(varOriginal);
// After this point, varOriginal is no longer valid
cout << endl;
return 0;
}