-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemory.cc
69 lines (60 loc) · 1.47 KB
/
memory.cc
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
#include <atomic>
#include <cassert>
#include <utility>
namespace ns {
template <class T> struct shared_ptr {
T *ptr;
std::atomic<int> *refcnt;
shared_ptr(T *p = nullptr) : ptr{p}, refcnt{new std::atomic<int>(1)} {}
shared_ptr(shared_ptr &other) : ptr{other.ptr}, refcnt{other.refcnt} {
if (ptr)
(*refcnt)++;
}
shared_ptr &operator=(shared_ptr &rhs) {
destruct();
ptr = rhs.ptr;
refcnt = rhs.refcnt;
if (ptr)
(*refcnt)++;
return *this;
}
shared_ptr(shared_ptr &&) = delete;
shared_ptr &operator=(shared_ptr &&) = delete;
~shared_ptr() { destruct(); }
void destruct() {
if (*refcnt > 1)
(*refcnt)--;
else {
delete refcnt;
delete ptr;
}
}
};
template <class T> struct unique_ptr {
T *ptr;
unique_ptr(T *ptr) : ptr{ptr} {}
unique_ptr(unique_ptr &) = delete;
unique_ptr &operator=(unique_ptr &) = delete;
unique_ptr(unique_ptr &&other) : ptr{other.ptr} { other.ptr = nullptr; };
unique_ptr &operator=(unique_ptr &&rhs) {
ptr = rhs.ptr;
rhs.ptr = nullptr;
return *this;
}
~unique_ptr() { delete ptr; }
};
} // namespace ns
int main() {
ns::shared_ptr<int> sp(new int(0));
assert(*sp.refcnt == 1);
{
ns::shared_ptr<int> sq = sp;
assert(*sq.refcnt == 2);
ns::shared_ptr<int> sr(sq);
assert(*sr.refcnt == 3);
}
assert(*sp.refcnt == 1);
ns::unique_ptr<int> up(new int(0));
ns::unique_ptr<int> uq = std::move(up);
ns::unique_ptr<int> ur(std::move(uq));
}