about summary refs log tree commit diff stats
diff options
context:
space:
mode:
-rw-r--r--hkutil/recptr.h89
1 files changed, 89 insertions, 0 deletions
diff --git a/hkutil/recptr.h b/hkutil/recptr.h new file mode 100644 index 0000000..c39e9d8 --- /dev/null +++ b/hkutil/recptr.h
@@ -0,0 +1,89 @@
1#ifndef RECPTR_H_BCF778F0
2#define RECPTR_H_BCF778F0
3
4namespace hatkirby {
5
6 /**
7 * This class provides a pointer wrapper for an object. The difference between
8 * it and std::unique_ptr is that it has a defined copy constructor, which
9 * uses the object's copy constructor to make a new object. This class is
10 * useful for the situation in which an object needs to have a member variable
11 * of the same type as itself.
12 */
13 template <typename T>
14 class recptr {
15 public:
16
17 recptr(T* ptr) : ptr_(ptr)
18 {
19 }
20
21 ~recptr()
22 {
23 delete ptr_;
24 }
25
26 recptr(const recptr& other)
27 : ptr_(new T(*other.ptr_))
28 {
29 }
30
31 recptr(recptr&& other)
32 {
33 std::swap(ptr_, other.ptr_);
34 }
35
36 recptr& operator=(const recptr& other)
37 {
38 if (ptr_)
39 {
40 delete ptr_;
41 }
42
43 ptr_ = new T(*other.ptr_);
44
45 return *this;
46 }
47
48 recptr& operator=(recptr&& other)
49 {
50 if (ptr_)
51 {
52 delete ptr_;
53
54 ptr_ = nullptr;
55 }
56
57 std::swap(ptr_, other.ptr_);
58
59 return *this;
60 }
61
62 T& operator*()
63 {
64 return *ptr_;
65 }
66
67 T* operator->()
68 {
69 return ptr_;
70 }
71
72 const T& operator*() const
73 {
74 return *ptr_;
75 }
76
77 const T* operator->() const
78 {
79 return ptr_;
80 }
81
82 private:
83
84 T* ptr_ = nullptr;
85 };
86
87}
88
89#endif /* end of include guard: RECPTR_H_BCF778F0 */