写一个 Move aware class

文章目录
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
class MyString {
public:
static size_t DCtor;
static size_t Ctor;
static size_t CCtor;
static size_t CAsgn;
static size_t MCtor;
static size_t Dtor;
private:
char* _data;
size_t _len;
void _init_data(const char *s) {
_data = new char[_len + 1];
memcpy(_data, s, _len);
_data[_len] = '\0';
}
public:
// default ctor
MyString(): _data(NULL), _len(0) {
++DCtor;
}
// ctor
MyString(const char* p): _len(strlen(p)) {
++Ctor;
_init_data(p);
}

// copy ctor
MyString(const Mystring& str):_len(str._len) {
++CCtor;
_init_data(str._data);
}

// move ctor
MyString(MyString&& str) noexcept
:_data(str._data), _len(str._len) {
++MCtor;
str._len = 0;
str._data = NULL;// IMPORTANT
}

// copy assignment
MyString& operator=(const MyString& str) {
++CAsgn;
if(this != &str) { // 自我赋值检查
if(_data) delete _data;
_len = str._len;
_init_data(str._data);
} else {

}
return *this;
}

// move assignment
MyString& operator=(MyString&& str) noexcept{
++MAsgn;
if(this != &str) { // 自我赋值检查
if(_data) delete _data;
_len = str._len;
_data = str._data;
str._len = 0;
str._data = NULL;
}
return *this;
}

// dtor
virtual ~MyString() {
++Dtor;
if(_data) delete _data;
}

// operator<
bool operator<(const MyString& rhs) const {
return string(this->data) < string(rhs._data);
}
// operator==
bool operator==(const MyString& rhs) const {
return string(this->data) == string(rhs._data);
}

char* get() const { return _data; }
}


size_t MyString::DCtor = 0;
size_t MyString::Ctor = 0;
size_t MyString::CCtor = 0;
size_t MyString::CAsgn = 0;
size_t MyString::MCtor = 0;
size_t MyString::Dtor = 0;
size_t MyString::MAsgn = 0;
namespace std {
template<>
struct hash<MyString> { // for unordered containers
size_t operator() (const MyString& s) const noexcept {
return hash<string>()(string(s.get()));
// 借用现成的 hash<string>
}
}
}