C++ API Reference RNBO: common/RNBO_UniquePtr.h Source File

RNBO: common/RNBO_UniquePtr.h Source File

1 //
2 // RNBO_UniquePtr.h
3 // Created: 30 Jun 2016 6:66:66pm
4 // Author: Jeremy Bernstein
5 //
6 //
7 
8 #ifndef _RNBO_UNIQUEPTR_H_
9 #define _RNBO_UNIQUEPTR_H_
10 
11 namespace RNBO {
12 
18  template <class T>
19  struct default_delete {
20 
26  void operator() (T* p) const
27  {
28  delete p;
29  }
30  };
31 
50  template <class T, class Deleter = default_delete<T> >
51  class UniquePtr {
52 
53  public:
54 
58  explicit UniquePtr(T* ptr = nullptr)
59  : _ptr(ptr)
60  {}
61 
68  reset(ptr);
69  return *this;
70  }
71 
79  _ptr = other._ptr;
80  other._ptr = nullptr;
81  }
82 
89  reset(other.release());
90  return *this;
91  }
92 
96  ~UniquePtr() { reset(); }
97 
101  void reset(T* ptr = nullptr) {
102  if (ptr == _ptr) return;
103 
104  T* old = _ptr;
105  _ptr = ptr;
106  if (old != nullptr) Deleter()(old);
107  }
108 
114  T* get() const { return _ptr; }
115 
121  T* release() { T* rv = _ptr; _ptr = nullptr; return rv; }
122 
126  T* operator->() const { return _ptr; }
127 
131  T& operator*() const { return *_ptr; }
132 
138  operator bool() const { return _ptr ? true : false; }
139 
140  // disable copy constructor and assignment operator
141  UniquePtr(const UniquePtr<T>& other) = delete;
142  UniquePtr<T>& operator=(const UniquePtr<T>& other) = delete;
143 
144  private:
145 
146  T* _ptr;
147  };
148 
149 }
150 
151 #endif // #ifndef _RNBO_UNIQUEPTR_H_