-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeferred_ptr.hpp
83 lines (82 loc) · 1.51 KB
/
deferred_ptr.hpp
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
#ifndef DEFERRED_PTR_HPP
#define DEFERRED_PTR_HPP
#include "deferred_base.hpp"
#include <forward_list>
template <typename T>
class deferred_ptr : private deferred_base {
public:
bool *alive = nullptr;
T *data = nullptr;
std::forward_list<deferred_base *> *roots = nullptr;
void mark() override
{
if (alive)
*alive = true;
}
void de_register()
{
if (roots)
roots->remove(this);
}
void do_register()
{
if (roots)
roots->push_front(this);
}
deferred_ptr(){}
deferred_ptr(bool *alive, T*data, std::forward_list<deferred_base*> *roots) : alive(alive) , data(data), roots(roots) {roots->push_front(this);}
deferred_ptr(const deferred_ptr &other)
{
if (this == &other) return;
alive = other.alive;
data = other.data;
roots = other.roots;
do_register();
}
const deferred_ptr &operator=(const deferred_ptr &other)
{
if (this == &other) return *this;
de_register();
alive = other.alive;
data = other.data;
roots = other.roots;
do_register();
return *this;
}
deferred_ptr(deferred_ptr &&other)
{
alive = other.alive;
data = other.data;
roots = other.roots;
do_register();
other.de_register();
}
deferred_ptr &operator=(deferred_ptr &&other)
{
if (this == &other) return *this;
de_register();
alive = other.alive;
data = other.data;
roots = other.roots;
do_register();
other.de_register();
return *this;
}
~deferred_ptr()
{
de_register();
}
T *operator->()
{
return data;
}
T &operator*()
{
return *data;
}
operator bool()
{
return data;
}
};
#endif