设计实现

设计实现

设计并实现一个LRU Cache

请简述智能指针原理,并实现一个简单的智能指针

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
class SmartPointer;
template<typename T>
class Counter {
friend class SmartPointer<T>;
private:
T* ptr;
int cnt;
public:
Counter() {
ptr = NULL;
cnt = 0;
}
Counter(T* p) {
ptr = p;
cnt = 1;
}
~Counter() {
delete ptr;
}
};
template <typename T>
class SmartPointer {
private:
Counter* ptr_counter;
public:
SmartPointer(T* p) {
ptr_counter = new Counter(p);
}
SmartPointer(const SmartPointer &sp) {
ptr_counter = sp.ptr_counter;
++ptr_count->cnt;
}
SmartPointer& operator=(const SmartPointer &sp) {
++sp.ptr_counter->cnt;
--ptr_counter->cnt;
if (ptr_counter->cnt == 0) {
delete ptr_counter;
}
ptr_counter = sp.ptr_counter;
}
~SmartPointer() {
--ptr_counter->cnt;
if (ptr_counter->cnt == 0) {
delete ptr_counter;
}
}
};

实现一个Memcpy函数