-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathrule_of_three.cpp
executable file
·90 lines (68 loc) · 1.9 KB
/
rule_of_three.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
#include <cstring>
#include <iostream>
/*
Rule of three
If a class requires a
user-defined destructor,
a user-defined copy constructor,
or a user-defined copy assignment operator,
it almost certainly requires all three.
*/
class rule_of_three
{
char* cstring; // raw pointer used as a handle to a dynamically-allocated memory block
void init(const char* s)
{
std::size_t n = std::strlen(s) + 1;
cstring = new char[n];
std::memcpy(cstring, s, n);
}
public:
rule_of_three(const char* s = "")
{
init(s);
}
/* user-defined destructor */
~rule_of_three()
{
delete[] cstring;
}
/* Copy constructor */
rule_of_three(const rule_of_three& other)
{
init(other.cstring);
}
/* Copy assignment (Assignment operator) */
rule_of_three& operator=(const rule_of_three& other)
{
if(this != &other) {
delete[] cstring; // deallocate
init(other.cstring);
}
return *this;
}
char* getCstring()
{
return this->cstring;
}
};
int main()
{
{
std::cout<< "===========================Copy assignment (Assignment operator)======================"<<std::endl;
rule_of_three rule_of_three_1("1");
rule_of_three rule_of_three_2("2");
std::cout<< rule_of_three_1.getCstring()<<std::endl;
std::cout<< rule_of_three_2.getCstring()<<std::endl;
rule_of_three_1=rule_of_three_2;
std::cout<<rule_of_three_1.getCstring() <<std::endl;
}
{
std::cout<< "===========================Copy operator======================"<<std::endl;
rule_of_three other("other");
rule_of_three rule_of_three_1 = other;
rule_of_three rule_of_three_2(other);
std::cout<<rule_of_three_1.getCstring() <<std::endl;
std::cout<<rule_of_three_2.getCstring() <<std::endl;
}
}