1 #ifndef MARISA_SCOPED_PTR_H_ 2 #define MARISA_SCOPED_PTR_H_ 3 4 #include "marisa/base.h" 5 6 namespace marisa { 7 8 template <typename T> 9 class scoped_ptr { 10 public: scoped_ptr()11 scoped_ptr() : ptr_(NULL) {} scoped_ptr(T * ptr)12 explicit scoped_ptr(T *ptr) : ptr_(ptr) {} 13 ~scoped_ptr()14 ~scoped_ptr() { 15 delete ptr_; 16 } 17 18 void reset(T *ptr = NULL) { 19 MARISA_DEBUG_IF((ptr != NULL) && (ptr == ptr_), MARISA_RESET_ERROR); 20 scoped_ptr(ptr).swap(*this); 21 } 22 23 T &operator*() const { 24 MARISA_DEBUG_IF(ptr_ == NULL, MARISA_STATE_ERROR); 25 return *ptr_; 26 } 27 T *operator->() const { 28 MARISA_DEBUG_IF(ptr_ == NULL, MARISA_STATE_ERROR); 29 return ptr_; 30 } get()31 T *get() const { 32 return ptr_; 33 } 34 clear()35 void clear() { 36 scoped_ptr().swap(*this); 37 } swap(scoped_ptr & rhs)38 void swap(scoped_ptr &rhs) { 39 marisa::swap(ptr_, rhs.ptr_); 40 } 41 42 private: 43 T *ptr_; 44 45 // Disallows copy and assignment. 46 scoped_ptr(const scoped_ptr &); 47 scoped_ptr &operator=(const scoped_ptr &); 48 }; 49 50 } // namespace marisa 51 52 #endif // MARISA_SCOPED_PTR_H_ 53