From b430eb58654298d17492a36c7bcda9f803a327fe Mon Sep 17 00:00:00 2001 From: Kelly Rauchenberger Date: Sun, 1 Apr 2018 11:32:01 -0400 Subject: Added recpt class --- hkutil/recptr.h | 89 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 hkutil/recptr.h 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 @@ +#ifndef RECPTR_H_BCF778F0 +#define RECPTR_H_BCF778F0 + +namespace hatkirby { + + /** + * This class provides a pointer wrapper for an object. The difference between + * it and std::unique_ptr is that it has a defined copy constructor, which + * uses the object's copy constructor to make a new object. This class is + * useful for the situation in which an object needs to have a member variable + * of the same type as itself. + */ + template + class recptr { + public: + + recptr(T* ptr) : ptr_(ptr) + { + } + + ~recptr() + { + delete ptr_; + } + + recptr(const recptr& other) + : ptr_(new T(*other.ptr_)) + { + } + + recptr(recptr&& other) + { + std::swap(ptr_, other.ptr_); + } + + recptr& operator=(const recptr& other) + { + if (ptr_) + { + delete ptr_; + } + + ptr_ = new T(*other.ptr_); + + return *this; + } + + recptr& operator=(recptr&& other) + { + if (ptr_) + { + delete ptr_; + + ptr_ = nullptr; + } + + std::swap(ptr_, other.ptr_); + + return *this; + } + + T& operator*() + { + return *ptr_; + } + + T* operator->() + { + return ptr_; + } + + const T& operator*() const + { + return *ptr_; + } + + const T* operator->() const + { + return ptr_; + } + + private: + + T* ptr_ = nullptr; + }; + +} + +#endif /* end of include guard: RECPTR_H_BCF778F0 */ -- cgit 1.4.1