-
Notifications
You must be signed in to change notification settings - Fork 0
/
moveable_str.cpp
118 lines (103 loc) · 2.59 KB
/
moveable_str.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
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
/*************************************************************************
> File Name: moveable_str.cpp
> Author: Feng
> Created Time: 2018/12/18 9:47:45
> Content:
************************************************************************/
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
class mystring
{
public:
mystring() : data_(nullptr), len_(0)
{
cout << "mystring()" << endl;
}
mystring(const char* str)
{
cout << "mystring(const char* str)" << endl;
len_ = strlen(str);
CopyData(str);
}
mystring(const mystring& other)
{
cout << "mystring(const mystring& other)" << endl;
if (other.data_) {
len_ = other.len_;
CopyData(other.data_);
}
}
mystring& operator=(const mystring& other)
{
cout << "mystring& operator=(const mystring& other)" << endl;
if (this != &other) {
len_ = other.len_;
DeleteData();
CopyData(other.data_);
}
return *this;
}
mystring(mystring&& other)
{
cout << "mystring(mystring&& other)" << endl;
if (this != &other) {
len_ = other.len_;
data_ = other.data_;
other.data_ = nullptr;
other.len_ = 0;
}
}
mystring& operator=(mystring&& other)
{
cout << "mystring& operator=(mystring&& other)" << endl;
if (this != &other) {
len_ = other.len_;
data_ = other.data_;
other.len_ = 0;
other.data_ = nullptr;
}
return *this;
}
~mystring()
{
cout << "~mystring()" << endl;
DeleteData();
}
private:
void CopyData(const char* str)
{
if (str) {
data_ = new char[len_ + 1];
memcpy(data_, str, len_);
data_[len_] = '\0';
}
}
void DeleteData()
{
if (data_) {
delete[] data_;
data_ = nullptr;
}
}
private:
char* data_;
size_t len_;
};
mystring func()
{
mystring str = "hello world";
return str;
}
int main()
{
mystring str1 = "c++";
mystring str2(str1); //拷贝构造函数
mystring str4(std::move(str1)); //转移构造函数(将str1强转成右值引用了)
mystring str5(std::forward<mystring>(str2));
cout << "-------------" << endl;
mystring str3 = func(); //我理解应该要在转移赋值,但是信息没打印,就是没走转移赋值,还没搞清楚
cout << "-------------" << endl;
return 0;
}