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
|
#include <iostream>
#include <algorithm>
#include <cstring>
class DynamicArray {
private:
int* arr;
size_t len;
public:
DynamicArray(size_t n = 0) : len(n), arr(n ? new int[n]() : nullptr) {
std::cout << "DynamicArray(" << n << ")\\n";
}
// 初始化列表构造函数
DynamicArray(std::initializer_list<int> list)
: len(list.size()), arr(new int[list.size()]) {
std::copy(list.begin(), list.end(), arr);
}
// 拷贝构造函数
DynamicArray(const DynamicArray& other)
: len(other.len), arr(other.len ? new int[other.len] : nullptr) {
std::copy(other.arr, other.arr + len, arr);
std::cout << "Copy constructor\\n";
}
// 移动构造函数
DynamicArray(DynamicArray&& other) noexcept
: arr(other.arr), len(other.len) {
other.arr = nullptr;
other.len = 0;
std::cout << "Move constructor\\n";
}
~DynamicArray() {
delete[] arr;
}
// 交换函数
friend void swap(DynamicArray& first, DynamicArray& second) noexcept {
using std::swap;
swap(first.arr, second.arr);
swap(first.len, second.len);
}
// Copy-and-Swap 赋值操作符
DynamicArray& operator=(DynamicArray other) noexcept {
swap(*this, other);
return *this;
}
void print() const {
std::cout << "[";
for (size_t i = 0; i < len; ++i) {
std::cout << arr[i] << (i < len - 1 ? ", " : "");
}
std::cout << "]\\n";
}
};
int main() {
DynamicArray arr1 = {1, 2, 3, 4, 5};
DynamicArray arr2 = {6, 7, 8};
std::cout << "Before assignment:\\n";
arr1.print(); // [1, 2, 3, 4, 5]
arr2.print(); // [6, 7, 8]
arr1 = arr2; // 拷贝赋值
std::cout << "After assignment:\\n";
arr1.print(); // [6, 7, 8]
arr2.print(); // [6, 7, 8]
DynamicArray arr3 = {9, 10, 11, 12};
arr1 = std::move(arr3); // 移动赋值
std::cout << "After move:\\n";
arr1.print(); // [9, 10, 11, 12]
arr3.print(); // [] (arr3被移动)
return 0;
}
|