-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvref.h
More file actions
85 lines (68 loc) · 1.45 KB
/
Copy pathvref.h
File metadata and controls
85 lines (68 loc) · 1.45 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
83
84
85
#ifndef VALEAN_VREF_
#define VALEAN_VREF_
#include <utility>
extern size_t vrefNextKey;
template<typename T>
class vowned;
template<typename T>
class vref;
template<typename T>
class vref_guard;
template<typename T>
class vref {
public:
vref(vowned<T>* own_) :
own(own_),
rememberedKey(own_->currentKey) {}
~vref() {}
vref_guard<T> open() {
return vref_guard<T>(own, rememberedKey);
}
private:
size_t rememberedKey;
vowned<T>* own;
};
template<typename T>
class vref_guard {
public:
vref_guard(vowned<T>* own_, size_t rememberedKey) :
own(own_) {
assert(rememberedKey == own->currentKey);
assert(own->present);
own->present = false;
}
~vref_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:
vowned<T>* own;
};
template<typename T>
class vowned {
public:
vowned(T contents_) :
present(true),
currentKey(vrefNextKey++),
contents(std::move(contents_)) {}
~vowned() {
assert(present);
}
vref<T> ref() {
return vref<T>(this);
}
private:
friend class vref<T>;
friend class vref_guard<T>;
bool present : 1;
size_t currentKey : 63;
T contents;
};
template<typename T, typename... P>
vowned<T> make_vowned(P&&... params) {
return vowned<T>(T(std::forward<P>(params)...));
}
#endif