-
Notifications
You must be signed in to change notification settings - Fork 0
/
PtrGuard.h
71 lines (55 loc) · 1.27 KB
/
PtrGuard.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
#ifndef CPPGCPTR_PTRGUARD_H
#define CPPGCPTR_PTRGUARD_H
#include "GCWorker.h"
#include "GCRegion.h"
template<typename T>
class PtrGuard {
private:
T* ptr;
GCRegion* region;
bool owns;
const bool relocationEnabled;
struct DeferGuard_t {
explicit DeferGuard_t() = default;
};
public:
static constexpr DeferGuard_t DeferGuard{};
PtrGuard(T* ptr, GCRegion* region, DeferGuard_t) :
ptr(ptr), region(region), owns(false),
relocationEnabled(GCWorker::getWorker()->relocationEnabled()) {
}
PtrGuard(T* ptr, GCRegion* region) : PtrGuard(ptr, region, DeferGuard) {
if (relocationEnabled)
lock();
}
~PtrGuard() {
unlock();
}
PtrGuard(const PtrGuard&) = delete;
PtrGuard(PtrGuard&&) noexcept = delete;
void lock() {
if (!owns) {
region->inc_use_count();
owns = true;
}
}
void unlock() {
if (owns) {
region->dec_use_count();
owns = false;
}
}
T* get() const {
return ptr;
}
T* operator->() const {
return ptr;
}
T& operator*() const {
return *ptr;
}
T* value() const {
return ptr;
}
};
#endif //CPPGCPTR_PTRGUARD_H