-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcref.h
85 lines (69 loc) · 1.34 KB
/
cref.h
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
#ifndef VALEAN_CREF_
#define VALEAN_CREF_
#include <utility>
template<typename T>
class cowned;
template<typename T>
class cref;
template<typename T>
class cref_guard;
template<typename T>
class cref {
public:
cref(cowned<T>* own_) :
own(own_) {
own->refCount++;
}
~cref() {
own->refCount--;
}
cref_guard<T> open() {
return cref_guard<T>(own);
}
private:
cowned<T>* own;
};
template<typename T>
class cref_guard {
public:
cref_guard(cowned<T>* own_) :
own(own_) {
assert(own->present);
own->present = false;
}
~cref_guard() {
own->present = true;
}
T& operator*() { return own->contents; }
const T& operator*() const { return own->contents; }
T* operator->() { return &own->contents; }
const T* operator->() const { return &own->contents; }
private:
cowned<T>* own;
};
template<typename T>
class cowned {
public:
cowned(T contents_) :
present(true),
refCount(0),
contents(std::move(contents_)) {}
~cowned() {
assert(present);
assert(refCount == 0);
}
cref<T> ref() {
return cref<T>(this);
}
private:
friend class cref<T>;
friend class cref_guard<T>;
bool present : 1;
size_t refCount : 63;
T contents;
};
template<typename T, typename... P>
cowned<T> make_cowned(P&&... params) {
return cowned<T>(T(std::forward<P>(params)...));
}
#endif