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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
|
#include <iostream>
#include <string>
#include <stdexcept>
// 异常安全的移动赋值实现
class SafeResourceManager
{
private:
int* data;
size_t size;
std::string name;
public:
SafeResourceManager(const std::string& n = "unnamed", size_t s = 0)
: name(n), size(s), data(nullptr)
{
if (size > 0)
{
data = new int[size];
for (size_t i = 0; i < size; ++i)
{
data[i] = static_cast<int>(i + 1);
}
}
std::cout << "Constructed: " << name << std::endl;
}
// 拷贝构造函数
SafeResourceManager(const SafeResourceManager& other)
: name(other.name + "_copy"), size(other.size), data(nullptr)
{
if (size > 0)
{
data = new int[size];
std::copy(other.data, other.data + size, data);
}
std::cout << "Copy constructed: " << name << std::endl;
}
// 移动构造函数
SafeResourceManager(SafeResourceManager&& other) noexcept
: data(other.data), size(other.size), name(std::move(other.name))
{
other.data = nullptr;
other.size = 0;
std::cout << "Move constructed: " << name << std::endl;
}
// 异常安全的拷贝赋值操作符(copy-and-swap idiom)
SafeResourceManager& operator=(const SafeResourceManager& other)
{
std::cout << "Copy assignment: " << name << " = " << other.name << std::endl;
if (this != &other)
{
SafeResourceManager temp(other); // 可能抛出异常
swap(temp); // 不抛出异常的交换
}
return *this;
}
// 移动赋值操作符(强异常安全保证)
SafeResourceManager& operator=(SafeResourceManager&& other) noexcept
{
std::cout << "Move assignment: " << name << " = " << other.name << std::endl;
if (this != &other)
{
// 使用swap确保异常安全
SafeResourceManager temp(std::move(other));
swap(temp);
}
return *this;
}
// 交换函数(不抛出异常)
void swap(SafeResourceManager& other) noexcept
{
std::swap(data, other.data);
std::swap(size, other.size);
std::swap(name, other.name);
}
~SafeResourceManager()
{
delete[] data;
std::cout << "Destroyed: " << name << std::endl;
}
void print() const
{
std::cout << "SafeResourceManager '" << name << "': size=" << size;
if (data && size > 0)
{
std::cout << ", first element=" << data[0];
}
std::cout << std::endl;
}
const std::string& getName() const { return name; }
size_t getSize() const { return size; }
bool hasData() const { return data != nullptr; }
};
// 全局swap函数(支持ADL)
void swap(SafeResourceManager& a, SafeResourceManager& b) noexcept
{
a.swap(b);
}
void ExceptionSafetyDemo()
{
std::cout << "=== Exception Safety Demo ===" << std::endl;
try
{
SafeResourceManager rm1("safe1", 5);
SafeResourceManager rm2("safe2", 3);
rm1.print();
rm2.print();
// 移动赋值(异常安全)
rm2 = std::move(rm1);
std::cout << "After safe move assignment:" << std::endl;
rm1.print();
rm2.print();
// 测试swap
std::cout << "\nTesting swap:" << std::endl;
SafeResourceManager rm3("swap_test1", 7);
SafeResourceManager rm4("swap_test2", 9);
rm3.print();
rm4.print();
swap(rm3, rm4);
std::cout << "After swap:" << std::endl;
rm3.print();
rm4.print();
}
catch (const std::exception& e)
{
std::cout << "Exception caught: " << e.what() << std::endl;
}
}
// 性能比较:拷贝赋值 vs 移动赋值
void PerformanceComparisonDemo()
{
std::cout << "\n=== Performance Comparison Demo ===" << std::endl;
const size_t iterations = 10000;
const size_t objectSize = 1000;
// 测试拷贝赋值性能
auto start = std::chrono::high_resolution_clock::now();
SafeResourceManager copyTarget("copy_target", objectSize);
for (size_t i = 0; i < iterations; ++i)
{
SafeResourceManager source("source_" + std::to_string(i), objectSize);
copyTarget = source; // 拷贝赋值
}
auto end = std::chrono::high_resolution_clock::now();
auto copyTime = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
// 测试移动赋值性能
start = std::chrono::high_resolution_clock::now();
SafeResourceManager moveTarget("move_target", objectSize);
for (size_t i = 0; i < iterations; ++i)
{
SafeResourceManager source("source_" + std::to_string(i), objectSize);
moveTarget = std::move(source); // 移动赋值
}
end = std::chrono::high_resolution_clock::now();
auto moveTime = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::cout << "Copy assignment time: " << copyTime.count() << " ms" << std::endl;
std::cout << "Move assignment time: " << moveTime.count() << " ms" << std::endl;
std::cout << "Speedup: " << (double)copyTime.count() / moveTime.count() << "x" << std::endl;
}
// 移动赋值的最佳实践
void BestPracticesDemo()
{
std::cout << "\n=== Best Practices Demo ===" << std::endl;
std::cout << "Move assignment operator best practices:" << std::endl;
std::cout << "1. Always check for self-assignment (this != &other)" << std::endl;
std::cout << "2. Mark as noexcept when possible" << std::endl;
std::cout << "3. Clean up existing resources before moving" << std::endl;
std::cout << "4. Leave moved-from object in valid state" << std::endl;
std::cout << "5. Return *this for chaining" << std::endl;
std::cout << "6. Consider using swap for exception safety" << std::endl;
std::cout << "7. Implement alongside move constructor" << std::endl;
// 演示正确的使用模式
std::cout << "\nCorrect usage patterns:" << std::endl;
SafeResourceManager rm1("pattern1", 5);
SafeResourceManager rm2("pattern2", 3);
SafeResourceManager rm3("pattern3", 7);
// 链式赋值
rm3 = rm2 = std::move(rm1);
std::cout << "After chained move assignment:" << std::endl;
rm1.print();
rm2.print();
rm3.print();
// 条件移动
bool shouldMove = true;
SafeResourceManager conditional("conditional", 4);
SafeResourceManager target("target", 2);
if (shouldMove)
{
target = std::move(conditional);
}
else
{
target = conditional;
}
std::cout << "After conditional move:" << std::endl;
conditional.print();
target.print();
}
int main()
{
ExceptionSafetyDemo();
PerformanceComparisonDemo();
BestPracticesDemo();
return 0;
}
|