-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil_unique_ptr.h
100 lines (87 loc) · 1.36 KB
/
util_unique_ptr.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
100
#pragma once
namespace util
{
/**
* Clase similar a std::unique_ptr.
*/
template <typename T>
class unique_ptr
{
T* ptr_ = nullptr;
template <typename U>
friend void swap(unique_ptr<U>&, unique_ptr<U>&);
public:
unique_ptr()
{}
unique_ptr(T* ptr)
: ptr_(ptr)
{}
~unique_ptr()
{
delete ptr_;
}
unique_ptr(unique_ptr<T>& u_ptr) = delete;
template <typename U>
unique_ptr(unique_ptr<U>&& u_ptr)
: unique_ptr(u_ptr.release())
{}
unique_ptr(unique_ptr<T>&& u_ptr)
: unique_ptr()
{
swap(*this, u_ptr);
}
unique_ptr<T>& operator=(unique_ptr<T> u_ptr)
{
swap(*this, u_ptr);
return *this;
}
/**
* Devuelve el puntero almacenado y deja de administrarlo.
*/
T* release()
{
auto ptr = ptr_;
ptr_ = nullptr;
return ptr;
}
/**
* Operador para dereferenciar.
*/
T& operator*() const
{
return *ptr_;
}
/**
* Operador para dereferenciar.
*/
T* operator->() const
{
return ptr_;
}
/**
* Devuelve si es válido.
*/
operator bool() const
{
return ptr_;
}
};
/**
* Funcion para swap.
*/
template <typename T>
void swap(unique_ptr<T>& lhs, unique_ptr<T>& rhs)
{
T* temp = lhs.ptr_;
lhs.ptr_ = rhs.ptr_;
rhs.ptr_ = temp;
}
/**
* Auxiliar como std::make_shared.
*/
template <typename T, typename... Args>
unique_ptr<T> make_unique(Args&&... args)
{
return unique_ptr<T>(new T(static_cast<Args&&>(args)...));
}
}