Boost.Locale
hold_ptr.hpp
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 
7 #ifndef BOOST_LOCALE_HOLD_PTR_H
8 #define BOOST_LOCALE_HOLD_PTR_H
9 
10 #include <boost/locale/config.hpp>
11 
12 namespace boost { namespace locale {
15  template<typename T>
16  class hold_ptr {
17  public:
19  hold_ptr() : ptr_(nullptr) {}
20 
22  explicit hold_ptr(T* v) : ptr_(v) {}
23 
25  ~hold_ptr() { delete ptr_; }
26 
27  // Non-copyable
28  hold_ptr(const hold_ptr&) = delete;
29  hold_ptr& operator=(const hold_ptr&) = delete;
30  // Movable
31  hold_ptr(hold_ptr&& other) noexcept : ptr_(other.ptr_) { other.ptr_ = nullptr; }
32  hold_ptr& operator=(hold_ptr&& other) noexcept
33  {
34  swap(other);
35  return *this;
36  }
37 
39  T const* get() const { return ptr_; }
41  T* get() { return ptr_; }
42 
44  explicit operator bool() const { return ptr_ != nullptr; }
45 
47  T const& operator*() const { return *ptr_; }
49  T& operator*() { return *ptr_; }
50 
52  T const* operator->() const { return ptr_; }
54  T* operator->() { return ptr_; }
55 
57  T* release()
58  {
59  T* tmp = ptr_;
60  ptr_ = nullptr;
61  return tmp;
62  }
63 
65  void reset(T* p = nullptr)
66  {
67  if(ptr_)
68  delete ptr_;
69  ptr_ = p;
70  }
71 
73  void swap(hold_ptr& other)
74  {
75  T* tmp = other.ptr_;
76  other.ptr_ = ptr_;
77  ptr_ = tmp;
78  }
79 
80  private:
81  T* ptr_;
82  };
83 
84 }} // namespace boost::locale
85 
86 #endif
hold_ptr()
Create new empty pointer.
Definition: hold_ptr.hpp:19
T const * operator->() const
Get a const pointer to the object.
Definition: hold_ptr.hpp:52
T * get()
Get a mutable pointer to the object.
Definition: hold_ptr.hpp:41
T const & operator *() const
Get a const reference to the object.
Definition: hold_ptr.hpp:47
T const * get() const
Get a const pointer to the object.
Definition: hold_ptr.hpp:39
hold_ptr(T *v)
Create a pointer that holds v, ownership is transferred to smart pointer.
Definition: hold_ptr.hpp:22
a smart pointer similar to std::unique_ptr but the underlying object has the same constness as the po...
Definition: hold_ptr.hpp:16
void reset(T *p=nullptr)
Set new value to pointer, previous object is destroyed, ownership on new object is transferred.
Definition: hold_ptr.hpp:65
~hold_ptr()
Destroy smart pointer and the object it owns.
Definition: hold_ptr.hpp:25
T * release()
Transfer an ownership on the pointer to user.
Definition: hold_ptr.hpp:57
void swap(hold_ptr &other)
Swap two pointers.
Definition: hold_ptr.hpp:73
T * operator->()
Get a mutable pointer to the object.
Definition: hold_ptr.hpp:54