-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathdptr.h
99 lines (94 loc) · 2.75 KB
/
dptr.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// Copyright (c) 2014 ipkn.
// Licensed under the MIT license.
#pragma once
#include "dumpableconf.h"
#include <cstddef>
#include <functional>
#include <tuple>
namespace dumpable
{
namespace detail
{
inline std::function<std::pair<void*, dumpable::ptrdiff_t>(void* self, dumpable::size_t size)>& dptr_alloc()
{
static std::function<std::pair<void*, dumpable::ptrdiff_t>(void* self, dumpable::size_t size)> allocFunc;
return allocFunc;
}
inline bool dumpable_is_custom_alloc()
{
return !!dptr_alloc();
}
}
template <typename T>
class dptr
{
private:
dumpable::ptrdiff_t diff_;
protected:
void* alloc_internal(dumpable::size_t size)
{
void* ret;
dumpable::ptrdiff_t offset;
std::tie(ret, offset) = detail::dptr_alloc()(this, size);
diff_ = offset;
return ret;
}
public:
dptr() : diff_(0) {}
dptr(const dptr<T>& rhs)
{
diff_ = (char*)&*rhs - (char*)this;
}
dptr(dptr<T>&& rhs) noexcept
{
diff_ = (char*)&*rhs - (char*)this;
rhs = nullptr;
}
T& operator* () const noexcept
{
if (diff_ == 0)
return *(T*)nullptr;
return *(T*)((char*)this + diff_);
}
T* operator-> () const noexcept
{
if (diff_ == 0)
return (T*)nullptr;
return (T*)((char*)this + diff_);
}
operator T* () const noexcept
{
if (diff_ == 0)
return (T*)nullptr;
return (T*)((char*)this + diff_);
}
dptr& operator = (T* x)
{
if (x == nullptr)
diff_ = 0;
else if (detail::dptr_alloc())
{
void* ret = alloc_internal(sizeof(T));
*(T*)ret = *x;
}
else
diff_ = (char*)x - (char*)this;
return *this;
}
dptr& operator = (const dptr<T>& dptr_x)
{
if (&dptr_x == this)
return *this;
T* x = &*dptr_x;
return (*this = x);
}
dptr& operator = (dptr<T>&& dptr_x) noexcept
{
if (&dptr_x == this)
return *this;
T* x = &*dptr_x;
dptr_x = nullptr;
return (*this = x);
}
};
}