hold_ptr.hpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. //
  2. // Copyright (c) 2010 Artyom Beilis (Tonkikh)
  3. //
  4. // Distributed under the Boost Software License, Version 1.0.
  5. // https://www.boost.org/LICENSE_1_0.txt
  6. #ifndef BOOST_LOCALE_HOLD_PTR_H
  7. #define BOOST_LOCALE_HOLD_PTR_H
  8. #include <boost/locale/config.hpp>
  9. namespace boost { namespace locale {
  10. /// \brief a smart pointer similar to std::unique_ptr but the
  11. /// underlying object has the same constness as the pointer itself (unlike an ordinary pointer).
  12. template<typename T>
  13. class hold_ptr {
  14. public:
  15. /// Create new empty pointer
  16. hold_ptr() : ptr_(nullptr) {}
  17. /// Create a pointer that holds \a v, ownership is transferred to smart pointer
  18. explicit hold_ptr(T* v) : ptr_(v) {}
  19. /// Destroy smart pointer and the object it owns.
  20. ~hold_ptr() { delete ptr_; }
  21. // Non-copyable
  22. hold_ptr(const hold_ptr&) = delete;
  23. hold_ptr& operator=(const hold_ptr&) = delete;
  24. // Movable
  25. hold_ptr(hold_ptr&& other) noexcept : ptr_(other.ptr_) { other.ptr_ = nullptr; }
  26. hold_ptr& operator=(hold_ptr&& other) noexcept
  27. {
  28. swap(other);
  29. return *this;
  30. }
  31. /// Get a const pointer to the object
  32. T const* get() const { return ptr_; }
  33. /// Get a mutable pointer to the object
  34. T* get() { return ptr_; }
  35. /// Explicitly convertible to bool. Returns: get() != nullptr
  36. explicit operator bool() const { return ptr_ != nullptr; }
  37. /// Get a const reference to the object
  38. T const& operator*() const { return *ptr_; }
  39. /// Get a mutable reference to the object
  40. T& operator*() { return *ptr_; }
  41. /// Get a const pointer to the object
  42. T const* operator->() const { return ptr_; }
  43. /// Get a mutable pointer to the object
  44. T* operator->() { return ptr_; }
  45. /// Transfer an ownership on the pointer to user
  46. T* release()
  47. {
  48. T* tmp = ptr_;
  49. ptr_ = nullptr;
  50. return tmp;
  51. }
  52. /// Set new value to pointer, previous object is destroyed, ownership on new object is transferred
  53. void reset(T* p = nullptr)
  54. {
  55. if(ptr_)
  56. delete ptr_;
  57. ptr_ = p;
  58. }
  59. /// Swap two pointers
  60. void swap(hold_ptr& other)
  61. {
  62. T* tmp = other.ptr_;
  63. other.ptr_ = ptr_;
  64. ptr_ = tmp;
  65. }
  66. private:
  67. T* ptr_;
  68. };
  69. }} // namespace boost::locale
  70. #endif