hold_ptr.hpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. namespace boost {
  11. namespace locale {
  12. ///
  13. /// \brief a smart pointer similar to std::auto_ptr but it is non-copyable and the
  14. /// underlying object has the same constness as the pointer itself (unlike an ordinary pointer).
  15. ///
  16. template<typename T>
  17. class hold_ptr {
  18. hold_ptr(hold_ptr const &other); // non copyable
  19. hold_ptr const &operator=(hold_ptr const &other); // non assignable
  20. public:
  21. ///
  22. /// Create new empty pointer
  23. ///
  24. hold_ptr() : ptr_(0) {}
  25. ///
  26. /// Create a pointer that holds \a v, ownership is transferred to smart pointer
  27. ///
  28. explicit hold_ptr(T *v) : ptr_(v) {}
  29. ///
  30. /// Destroy smart pointer and the object it owns.
  31. ///
  32. ~hold_ptr()
  33. {
  34. delete ptr_;
  35. }
  36. ///
  37. /// Get a const pointer to the object
  38. ///
  39. T const *get() const { return ptr_; }
  40. ///
  41. /// Get a mutable pointer to the object
  42. ///
  43. T *get() { return ptr_; }
  44. ///
  45. /// Get a const reference to the object
  46. ///
  47. T const &operator *() const { return *ptr_; }
  48. ///
  49. /// Get a mutable reference to the object
  50. ///
  51. T &operator *() { return *ptr_; }
  52. ///
  53. /// Get a const pointer to the object
  54. ///
  55. T const *operator->() const { return ptr_; }
  56. ///
  57. /// Get a mutable pointer to the object
  58. ///
  59. T *operator->() { return ptr_; }
  60. ///
  61. /// Transfer an ownership on the pointer to user
  62. ///
  63. T *release() { T *tmp=ptr_; ptr_=0; return tmp; }
  64. ///
  65. /// Set new value to pointer, previous object is destroyed, ownership on new object is transferred
  66. ///
  67. void reset(T *p=0)
  68. {
  69. if(ptr_) delete ptr_;
  70. ptr_=p;
  71. }
  72. /// Swap two pointers
  73. void swap(hold_ptr &other)
  74. {
  75. T *tmp=other.ptr_;
  76. other.ptr_=ptr_;
  77. ptr_=tmp;
  78. }
  79. private:
  80. T *ptr_;
  81. };
  82. } // locale
  83. } // boost
  84. #endif
  85. // vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4