-
Notifications
You must be signed in to change notification settings - Fork 0
/
testmove.cpp
151 lines (128 loc) · 2.51 KB
/
testmove.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
#include <utility>
#include <string.h>
#include <iostream>
#include <vector>
using namespace std;
class String
{
public:
String()
: data_(new char[1])
{
*data_ = '\0';
}
String(const char* str)
: data_(new char[strlen(str) + 1])
{
strcpy_s(data_,strlen(str) + 1, str);
}
String(const String& rhs)
: data_(new char[rhs.size() + 1])
{
cout<<"copy constructor, data address is "<<static_cast<const void*>(data_)<<endl;
strcpy_s(data_, rhs.size() + 1, rhs.c_str());
}
/* Delegate constructor in C++11
String(const String& rhs)
: String(rhs.data_)
{
}
*/
~String()
{
delete[] data_;
}
String& operator=(const String& rhs)
{
String tmp(rhs);
swap(tmp);
return *this;
}
/* Traditional:String& operator=(String rhs)
{
swap(rhs);
return *this;
}*/
// C++ 11
String(String&& rhs)
: data_(rhs.data_)
{
cout<<"move constructor, data address is "<<static_cast<const void*>(data_)<<endl;
rhs.data_ = nullptr;
}
String& operator=(String&& rhs)
{
swap(rhs);
cout<<"move assignment, data address is "<<static_cast<const void*>(data_)<<endl;
return *this;
}
// Accessors
size_t size() const
{
return strlen(data_);
}
const char* c_str() const
{
return data_;
}
void swap(String& rhs)
{
std::swap(data_, rhs.data_);
}
friend ostream& operator<< (ostream& os, const String& str)
{
os<<"data_ address is "<<static_cast<const void*>(str.data_)<<", string is "<<str.data_<<endl;
return os;
}
private:
char* data_;
};
void foo(String x)
{
}
void bar(const String& x)
{
}
String baz()
{
String ret("world");
cout<<"calling baz()"<<endl;
return ret;
}
int main()
{
String s0;
cout << "s0" << s0 <<endl;
String s1("hello");
cout << "s1 " << s1 <<endl;
String s2(s0);
cout << "s2 " << s2 <<endl;
String s3 = s1;
cout << "s3 " << s3 <<endl;
s2 = s1;
cout<<"after s2 = s1" << " s2 " << s2 <<endl;
String s5;
s5 = std::move(baz());
cout << "s3 " << s3 <<endl;
String s6;
s6 = std::forward<String&>(s3);
cout << "s6 " << s6 <<endl;
String s7;
s7 = std::move(s3);
cout << "s7 " << s7 <<endl;
foo(s1);
bar(s1);
foo("temporary");
bar("temporary");
String s4 = baz();
cout<<"s4 " <<s4<<endl;
vector<String> svec;
cout<<"push 1"<<endl;
svec.push_back(s0);
cout<<"push 2"<<endl;
svec.push_back(s1);
cout<<"push 3"<<endl;
svec.push_back(baz());
cout<<"push 4"<<endl;
svec.push_back("good job");
}