hold_ptr.hpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. #include <boost/core/exchange.hpp>
  10. namespace boost { namespace locale {
  11. /// \brief a smart pointer similar to std::unique_ptr but the
  12. /// underlying object has the same constness as the pointer itself (unlike an ordinary pointer).
  13. template<typename T>
  14. class hold_ptr {
  15. public:
  16. /// Create new empty pointer
  17. hold_ptr() : ptr_(nullptr) {}
  18. /// Create a pointer that holds \a v, ownership is transferred to smart pointer
  19. explicit hold_ptr(T* v) : ptr_(v) {}
  20. /// Destroy smart pointer and the object it owns.
  21. ~hold_ptr() { delete ptr_; }
  22. // Non-copyable
  23. hold_ptr(const hold_ptr&) = delete;
  24. hold_ptr& operator=(const hold_ptr&) = delete;
  25. // Movable
  26. hold_ptr(hold_ptr&& other) noexcept : ptr_(exchange(other.ptr_, nullptr)) {}
  27. hold_ptr& operator=(hold_ptr&& other) noexcept
  28. {
  29. swap(other);
  30. return *this;
  31. }
  32. /// Get a const pointer to the object
  33. T const* get() const { return ptr_; }
  34. /// Get a mutable pointer to the object
  35. T* get() { return ptr_; }
  36. /// Explicitly convertible to bool. Returns: get() != nullptr
  37. explicit operator bool() const { return ptr_ != nullptr; }
  38. /// Get a const reference to the object
  39. T const& operator*() const { return *ptr_; }
  40. /// Get a mutable reference to the object
  41. T& operator*() { return *ptr_; }
  42. /// Get a const pointer to the object
  43. T const* operator->() const { return ptr_; }
  44. /// Get a mutable pointer to the object
  45. T* operator->() { return ptr_; }
  46. /// Transfer ownership of the pointer to user
  47. T* release() { return exchange(ptr_, nullptr); }
  48. /// Set new value to pointer, previous object is destroyed, ownership of new object is transferred
  49. void reset(T* p = nullptr)
  50. {
  51. if(ptr_)
  52. delete ptr_;
  53. ptr_ = p;
  54. }
  55. /// Swap two pointers
  56. void swap(hold_ptr& other) noexcept { ptr_ = exchange(other.ptr_, ptr_); }
  57. private:
  58. T* ptr_;
  59. };
  60. }} // namespace boost::locale
  61. #endif