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#include <boost/core/exchange.hpp>
12
13namespace boost { namespace locale {
16 template<typename T>
17 class hold_ptr {
18 public:
20 hold_ptr() : ptr_(nullptr) {}
21
23 explicit hold_ptr(T* v) : ptr_(v) {}
24
26 ~hold_ptr() { delete ptr_; }
27
28 // Non-copyable
29 hold_ptr(const hold_ptr&) = delete;
30 hold_ptr& operator=(const hold_ptr&) = delete;
31 // Movable
32 hold_ptr(hold_ptr&& other) noexcept : ptr_(exchange(other.ptr_, nullptr)) {}
33 hold_ptr& operator=(hold_ptr&& other) noexcept
34 {
35 swap(other);
36 return *this;
37 }
38
40 T const* get() const { return ptr_; }
42 T* get() { return ptr_; }
43
45 explicit operator bool() const { return ptr_ != nullptr; }
46
48 T const& operator*() const { return *ptr_; }
50 T& operator*() { return *ptr_; }
51
53 T const* operator->() const { return ptr_; }
55 T* operator->() { return ptr_; }
56
59 {
60 T* tmp = ptr_;
61 ptr_ = nullptr;
62 return tmp;
63 }
64
66 void reset(T* p = nullptr)
67 {
68 if(ptr_)
69 delete ptr_;
70 ptr_ = p;
71 }
72
74 void swap(hold_ptr& other) noexcept
75 {
76 T* tmp = other.ptr_;
77 other.ptr_ = ptr_;
78 ptr_ = tmp;
79 }
80
81 private:
82 T* ptr_;
83 };
84
85}} // namespace boost::locale
86
87#endif
a smart pointer similar to std::unique_ptr but the underlying object has the same constness as the po...
Definition: hold_ptr.hpp:17
hold_ptr(T *v)
Create a pointer that holds v, ownership is transferred to smart pointer.
Definition: hold_ptr.hpp:23
T const & operator*() const
Get a const reference to the object.
Definition: hold_ptr.hpp:48
void swap(hold_ptr &other) noexcept
Swap two pointers.
Definition: hold_ptr.hpp:74
T * operator->()
Get a mutable pointer to the object.
Definition: hold_ptr.hpp:55
T const * operator->() const
Get a const pointer to the object.
Definition: hold_ptr.hpp:53
hold_ptr()
Create new empty pointer.
Definition: hold_ptr.hpp:20
void reset(T *p=nullptr)
Set new value to pointer, previous object is destroyed, ownership on new object is transferred.
Definition: hold_ptr.hpp:66
T * release()
Transfer an ownership on the pointer to user.
Definition: hold_ptr.hpp:58
T * get()
Get a mutable pointer to the object.
Definition: hold_ptr.hpp:42
~hold_ptr()
Destroy smart pointer and the object it owns.
Definition: hold_ptr.hpp:26
T & operator*()
Get a mutable reference to the object.
Definition: hold_ptr.hpp:50
T const * get() const
Get a const pointer to the object.
Definition: hold_ptr.hpp:40