blob: fc0c419c96c07e964d580396e92a6bbb67c97d41 (
plain) (
blame)
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
|
#ifndef VSHAREDPTR_H
#define VSHAREDPTR_H
#include <cassert>
#include <memory>
#include <atomic>
template <typename T, typename Rc>
class vshared_ptr {
struct model {
Rc mRef{1};
model() = default;
template <class... Args>
explicit model(Args&&... args) : mValue(std::forward<Args>(args)...){}
explicit model(const T& other) : mValue(other){}
T mValue;
};
model* mModel{nullptr};
public:
using element_type = T;
vshared_ptr() = default;
~vshared_ptr()
{
unref();
}
template <class... Args>
explicit vshared_ptr(Args&&... args) : mModel(new model(std::forward<Args>(args)...))
{
}
vshared_ptr(const vshared_ptr& x) noexcept : vshared_ptr()
{
if (x.mModel) {
mModel = x.mModel;
++mModel->mRef;
}
}
vshared_ptr(vshared_ptr&& x) noexcept : vshared_ptr()
{
if (x.mModel) {
mModel = x.mModel;
x.mModel = nullptr;
}
}
auto operator=(const vshared_ptr& x) noexcept -> vshared_ptr&
{
unref();
mModel = x.mModel;
ref();
return *this;
}
auto operator=(vshared_ptr&& x) noexcept -> vshared_ptr&
{
unref();
mModel = x.mModel;
x.mModel = nullptr;
return *this;
}
operator bool() const noexcept {
return mModel != nullptr;
}
auto operator*() const noexcept -> element_type& { return read(); }
auto operator-> () const noexcept -> element_type* { return &read(); }
std::size_t refCount() const noexcept
{
assert(mModel);
return mModel->mRef;
}
bool unique() const noexcept
{
assert(mModel);
return mModel->mRef == 1;
}
private:
auto read() const noexcept -> element_type&
{
assert(mModel);
return mModel->mValue;
}
void ref()
{
if (mModel) ++mModel->mRef;
}
void unref()
{
if (mModel && (--mModel->mRef == 0)) {
delete mModel;
mModel = nullptr;
}
}
};
// atomic ref counted pointer implementation.
template < typename T>
using arc_ptr = vshared_ptr<T, std::atomic<std::size_t>>;
// ref counter pointer implementation.
template < typename T>
using rc_ptr = vshared_ptr<T, std::size_t>;
#endif // VSHAREDPTR_H
|