-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path13_2_Move.cpp
More file actions
135 lines (132 loc) · 2.1 KB
/
13_2_Move.cpp
File metadata and controls
135 lines (132 loc) · 2.1 KB
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
#include <stdlib.h>
#include <iostream>
#include <vector>
using namespace std;
class MyString
{
int id;
int size;
int length;
char* data;
public:
static int cnt;
MyString() : size(0), length(0), data(nullptr), id(++cnt) { cout << "빈 문자열 생성\n"; }
MyString(const char* str)
{
id = ++cnt;
cout << id << " 문자열 생성\n";
size = length = strlen(str);
data = new char[length];
for (int i = 0; i < length; ++i)
{
data[i] = str[i];
}
}
MyString(const MyString& str)
{
id = ++cnt;
cout << id << " 복사 생성\n";
size = str.size;
length = str.length;
if (size < length)
{
size = length;
}
data = new char[size];
for (int i = 0; i < length; ++i)
{
data[i] = str.data[i];
}
id = ++cnt;
}
MyString(MyString&& ref) noexcept
{
id = ++cnt;
cout << id << " 이동 생성\n";
size = ref.size;
length = ref.length;
if (size < length)
{
size = length;
}
data = ref.data;
ref.length = 0;
ref.size = 0;
ref.data = nullptr;
}
~MyString()
{
cout << id << "해제\n";
--cnt;
if (data)
{
delete[] data;
}
}
MyString& operator=(const MyString& str)
{
cout << "복사\n";
if (size < str.length)
{
delete[] data;
size = str.length;
data = new char[size];
}
length = str.length;
for (int i = 0; i < length; ++i)
{
data[i] = str.data[i];
}
return (*this);
}
MyString& operator=(MyString&& str) noexcept
{
cout << "이동\n";
delete[] data;
size = str.size;
length = str.length;
if (size < length)
{
size = length;
}
data = str.data;
str.data = nullptr;
return (*this);
}
int Length() const
{
return length;
}
void Print() const
{
cout << "id: " << id << '\t';
for (int i = 0; i < length; ++i)
{
cout << data[i];
}
cout << "\n";
}
};
int MyString::cnt = 0;
template <typename T>
void MySwap(T& a, T& b)
{
T tmp(move(a));
a = move(b);
b = move(tmp);
}
int main(void)
{
MyString str1("abc");
MyString str2("def");
cout << "str1: ";
str1.Print();
cout << "str2: ";
str2.Print();
cout << "===SWAP===\n";
MySwap(str1, str2);
cout << "str1: ";
str1.Print();
cout << "str2: ";
str2.Print();
}