1 // 2 // Copyright (c) 2010 Artyom Beilis (Tonkikh) 3 // 4 // Distributed under the Boost Software License, Version 1.0. (See 5 // accompanying file LICENSE_1_0.txt or copy at 6 // http://www.boost.org/LICENSE_1_0.txt) 7 // 8 #ifndef BOOST_LOCALE_HOLD_PTR_H 9 #define BOOST_LOCALE_HOLD_PTR_H 10 11 namespace boost { 12 namespace locale { 13 /// 14 /// \brief a smart pointer similar to std::auto_ptr but it is non-copyable and the 15 /// underlying object has the same constness as the pointer itself (unlike an ordinary pointer). 16 /// 17 template<typename T> 18 class hold_ptr { 19 hold_ptr(hold_ptr const &other); // non copyable 20 hold_ptr const &operator=(hold_ptr const &other); // non assignable 21 public: 22 /// 23 /// Create new empty pointer 24 /// hold_ptr()25 hold_ptr() : ptr_(0) {} 26 /// 27 /// Create a pointer that holds \a v, ownership is transferred to smart pointer 28 /// hold_ptr(T * v)29 explicit hold_ptr(T *v) : ptr_(v) {} 30 31 /// 32 /// Destroy smart pointer and the object it owns. 33 /// ~hold_ptr()34 ~hold_ptr() 35 { 36 delete ptr_; 37 } 38 39 /// 40 /// Get a const pointer to the object 41 /// get() const42 T const *get() const { return ptr_; } 43 /// 44 /// Get a mutable pointer to the object 45 /// get()46 T *get() { return ptr_; } 47 48 /// 49 /// Get a const reference to the object 50 /// operator *() const51 T const &operator *() const { return *ptr_; } 52 /// 53 /// Get a mutable reference to the object 54 /// operator *()55 T &operator *() { return *ptr_; } 56 /// 57 /// Get a const pointer to the object 58 /// operator ->() const59 T const *operator->() const { return ptr_; } 60 /// 61 /// Get a mutable pointer to the object 62 /// operator ->()63 T *operator->() { return ptr_; } 64 65 /// 66 /// Transfer an ownership on the pointer to user 67 /// release()68 T *release() { T *tmp=ptr_; ptr_=0; return tmp; } 69 70 /// 71 /// Set new value to pointer, previous object is destroyed, ownership on new object is transferred 72 /// reset(T * p=0)73 void reset(T *p=0) 74 { 75 if(ptr_) delete ptr_; 76 ptr_=p; 77 } 78 /// Swap two pointers swap(hold_ptr & other)79 void swap(hold_ptr &other) 80 { 81 T *tmp=other.ptr_; 82 other.ptr_=ptr_; 83 ptr_=tmp; 84 } 85 private: 86 T *ptr_; 87 }; 88 89 } // locale 90 } // boost 91 92 #endif 93 // vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 94