-
Notifications
You must be signed in to change notification settings - Fork 0
/
UniquePtr.hpp
83 lines (64 loc) · 1.85 KB
/
UniquePtr.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
#pragma once
#include <functional>
template <typename Tp>
class UniquePtr
{
static void get_rid_of(Tp* ptr) { delete ptr; }
public:
using pointer = Tp*;
using element_type = Tp;
using deleter = std::function<void(Tp*)>;
UniquePtr()
: _ptr(nullptr),
_dltr(std::bind(&UniquePtr::get_rid_of, std::placeholders::_1)){};
UniquePtr(pointer ptr)
: _ptr(ptr),
_dltr(std::bind(&UniquePtr::get_rid_of, std::placeholders::_1)){};
UniquePtr(Tp* ptr, deleter&& dltr)
: _ptr(ptr), _dltr(std::forward<deleter>(dltr)){};
UniquePtr(UniquePtr&& other)
: _ptr(std::move(other._ptr)), _dltr(std::move(other._dltr))
{
other._ptr = nullptr;
};
UniquePtr& operator=(UniquePtr&& other)
{
reset(other.release());
_dltr = std::forward<deleter>(other._dltr);
return *this;
};
UniquePtr(const UniquePtr&) = delete;
UniquePtr operator=(const UniquePtr&) = delete;
~UniquePtr() { reset(nullptr); }
public:
pointer get() const { return _ptr; }
deleter& get_deleter() { return _dltr; }
const deleter& get_deleter() const { return _dltr; }
pointer release() noexcept
{
pointer ptr = _ptr;
_ptr = nullptr;
return ptr;
};
void reset(pointer ptr = pointer()) noexcept
{
if (_ptr)
_dltr(_ptr);
_ptr = ptr;
};
void swap(UniquePtr& other) noexcept
{
std::swap(_ptr, other._ptr);
std::swap(_dltr, other._dltr);
};
explicit operator bool() const noexcept { return get(); };
typename std::add_lvalue_reference<element_type>::type operator*() const
noexcept(noexcept(*std::declval<pointer>()))
{
return *get();
};
pointer operator->() const noexcept { return get(); };
private:
pointer _ptr;
deleter _dltr;
};