diff options
| author | Kelly Rauchenberger <fefferburbia@gmail.com> | 2018-04-01 11:32:01 -0400 |
|---|---|---|
| committer | Kelly Rauchenberger <fefferburbia@gmail.com> | 2018-04-01 11:32:01 -0400 |
| commit | b430eb58654298d17492a36c7bcda9f803a327fe (patch) | |
| tree | 127fdbd363eeac878012f65faed55433f7098c1d | |
| parent | eb30ce13012108fe38709cdf0732aa8b2ec2d52e (diff) | |
| download | hkutil-b430eb58654298d17492a36c7bcda9f803a327fe.tar.gz hkutil-b430eb58654298d17492a36c7bcda9f803a327fe.tar.bz2 hkutil-b430eb58654298d17492a36c7bcda9f803a327fe.zip | |
Added recpt class
| -rw-r--r-- | hkutil/recptr.h | 89 |
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 | |||
| 4 | namespace 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 */ | ||
