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
58 T* release() { return exchange(ptr_, nullptr); }
59
61 void reset(T* p = nullptr)
62 {
63 if(ptr_)
64 delete ptr_;
65 ptr_ = p;
66 }
67
69 void swap(hold_ptr& other) noexcept { ptr_ = exchange(other.ptr_, ptr_); }
70
71 private:
72 T* ptr_;
73 };
74
75}} // namespace boost::locale
76
77#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:69
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 of new object is transferred.
Definition: hold_ptr.hpp:61
T * release()
Transfer ownership of 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