-
Notifications
You must be signed in to change notification settings - Fork 940
Expand file tree
/
Copy pathmain.cpp
More file actions
82 lines (67 loc) · 2.4 KB
/
main.cpp
File metadata and controls
82 lines (67 loc) · 2.4 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
#include "../exercise.h"
// READ: 左值右值(概念)<https://learn.microsoft.com/zh-cn/cpp/c-language/l-value-and-r-value-expressions?view=msvc-170>
// READ: 左值右值(细节)<https://zh.cppreference.com/w/cpp/language/value_category>
// READ: 关于移动语义 <https://learn.microsoft.com/zh-cn/cpp/cpp/rvalue-reference-declarator-amp-amp?view=msvc-170#move-semantics>
// READ: 如果实现移动构造 <https://learn.microsoft.com/zh-cn/cpp/cpp/move-constructors-and-move-assignment-operators-cpp?view=msvc-170>
// READ: 移动构造函数 <https://zh.cppreference.com/w/cpp/language/move_constructor>
// READ: 移动赋值 <https://zh.cppreference.com/w/cpp/language/move_assignment>
// READ: 运算符重载 <https://zh.cppreference.com/w/cpp/language/operators>
class DynFibonacci {
size_t *cache;
int cached;
public:
// 动态设置容量的构造器
DynFibonacci(int capacity) : cache(new size_t[capacity]), cached(1) {
cache[0] = 0;
cache[1] = 1;
}
// 移动构造器
DynFibonacci(DynFibonacci&& other) noexcept
: cache(other.cache), cached(other.cached) {
other.cache = nullptr;
other.cached = 0;
}
// 移动赋值运算符
DynFibonacci& operator=(DynFibonacci&& other) noexcept {
if (this != &other) {
delete[] cache;
cache = other.cache;
cached = other.cached;
other.cache = nullptr;
other.cached = 0;
}
return *this;
}
// 析构器
~DynFibonacci() {
delete[] cache;
}
// 缓存优化的斐波那契计算
size_t operator[](int i) {
while (cached < i) {
++cached;
cache[cached] = cache[cached - 1] + cache[cached - 2];
}
return cache[i];
}
size_t operator[](int i) const {
ASSERT(i <= cached, "i out of range");
return cache[i];
}
bool is_alive() const {
return cache;
}
};
int main(int argc, char **argv) {
DynFibonacci fib(12);
ASSERT(fib[10] == 55, "fibonacci(10) should be 55");
DynFibonacci const fib_ = std::move(fib);
ASSERT(!fib.is_alive(), "Object moved");
ASSERT(fib_[10] == 55, "fibonacci(10) should be 55");
DynFibonacci fib0(6);
DynFibonacci fib1(12);
fib0 = std::move(fib1);
fib0 = std::move(fib0);
ASSERT(fib0[10] == 55, "fibonacci(10) should be 55");
return 0;
}