-
Notifications
You must be signed in to change notification settings - Fork 0
/
RaiiPtr.hpp
68 lines (51 loc) · 1009 Bytes
/
RaiiPtr.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
#pragma once
#include <utility>
namespace My {
/**
* @brief RAII模式的可移动资源指针模板类。
*/
template<typename T, void (*free)(T*)>
class RaiiPtr
{
public:
RaiiPtr(T* p = nullptr) noexcept
: _(p)
{
}
RaiiPtr(const RaiiPtr&) = delete;
RaiiPtr(RaiiPtr&& other) noexcept
: RaiiPtr()
{
swap(other);
}
~RaiiPtr() noexcept
{
if (_ != nullptr)
free(_);
}
operator bool() const { return _ != nullptr; }
operator T*() const { return _; }
RaiiPtr& operator=(const RaiiPtr&) = delete;
RaiiPtr& operator=(RaiiPtr&& other) noexcept
{
swap(*this, other);
return *this;
}
T* operator->() const { return _; }
T& operator*() const { return *operator->(); }
T* operator+() const { return operator->(); }
T* operator-()
{
auto p = _;
_ = nullptr;
return p;
}
friend void swap(RaiiPtr& lhs, RaiiPtr& rhs) noexcept
{
using std::swap;
swap(lhs._, rhs._);
}
private:
T* _;
};
} // namespace My