1
+ #include < iostream>
2
+ #include < string>
3
+ using namespace std ;
4
+
5
+ class MyString {
6
+ public:
7
+ static size_t DCtor; // 记录默认构造的调用次数
8
+ static size_t Ctor; // 记录ctor的调用次数
9
+ static size_t CCtor; // 记录copy ctor的调用次数
10
+ static size_t CAsgn; // 记录copy asgn的调用次数
11
+ static size_t MCtor; // 记录move-ctor的调用次数
12
+ static size_t MAsgn; // 记录move-asgn的调用次数
13
+ static size_t Dtor; // 记录dtor的调用次数
14
+ private:
15
+ char * _data;
16
+ size_t _len;
17
+ void _init_data (const char *s) {
18
+ _data = new char [_len+1 ];
19
+ memcpy (_data, s, _len);
20
+ _data[_len] = ' \0 ' ;
21
+ }
22
+ public:
23
+ // 默认构造
24
+ MyString (): _data(NULL ), _len(0 ) {++DCtor;}
25
+ // 构造
26
+ MyString (const char * p) : _len(strlen(p)) {
27
+ ++Ctor;
28
+ _init_data (p);
29
+ }
30
+ // 拷贝构造
31
+ MyString (const MyString& str): _len(str._len) {
32
+ ++CCtor;
33
+ _init_data (str._data );
34
+ }
35
+ // copy assignment 拷贝赋值
36
+ MyString& operator =(const MyString& str){
37
+ ++CAsgn;
38
+ if (this ==&str) {
39
+ return *this ;
40
+ }
41
+ if (_data) delete _data;
42
+ _len = str._len ;
43
+ _init_data (str._data );
44
+ return *this ;
45
+ }
46
+ // move 构造 with noexcept
47
+ MyString (MyString&& str) noexcept
48
+ // 把指针拷贝一下 长度拷贝一下
49
+ :_data(str._data), _len(str._len){
50
+ ++MCtor;
51
+ // 删除指针,如果不删除的话 如果右值被析构的时候编译器会调用析构函数把move的数据给回收
52
+ // 配合析构函数来看
53
+ str._len = 0 ;
54
+ str._data = NULL ; // 重要
55
+ }
56
+ // move assignment
57
+ MyString& operator =(MyString&& str) noexcept {
58
+ ++MAsgn;
59
+ // move
60
+ if (this !=&str) {
61
+ if (_data) delete _data;
62
+ _len = str._len ;
63
+ _data = str._data ;
64
+ str._len = 0 ;
65
+ str._data = NULL ; // 重要
66
+ }
67
+ return *this ;
68
+ }
69
+
70
+ // 析构函数
71
+ virtual ~MyString () {
72
+ ++DCtor;
73
+ if (_data) delete _data;
74
+ }
75
+
76
+ bool operator < (const MyString& rhs) const {
77
+ return string (this ->_data ) < string (rhs._data );
78
+ }
79
+
80
+ bool operator ==(const MyString& rhs) const {
81
+ return string (this ->_data ) == string (rhs._data );
82
+ }
83
+
84
+ char * get () const {
85
+ return _data;
86
+ }
87
+ };
88
+ size_t MyString::DCtor = 0 ;
89
+ size_t MyString::Ctor = 0 ;
90
+ size_t MyString::CCtor = 0 ;
91
+ size_t MyString::CAsgn = 0 ;
92
+ size_t MyString::MCtor = 0 ;
93
+ size_t MyString::Dtor = 0 ;
94
+
95
+ int main () {
96
+
97
+ }
0 commit comments