24bccb0438a517b59a9c9a8b4d70c9149a87380c
[dcpomatic.git] / src / wx / wx_ptr.h
1 /*
2     Copyright (C) 2023 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21
22 #ifndef DCPOMATIC_WX_PTR_H
23 #define DCPOMATIC_WX_PTR_H
24
25
26 #include "lib/dcpomatic_assert.h"
27 #include <utility>
28
29
30 template <class T>
31 class wx_ptr
32 {
33 public:
34         wx_ptr() {}
35
36         explicit wx_ptr(T* wx)
37                 : _wx(wx)
38         {}
39
40         wx_ptr(wx_ptr&) = delete;
41         wx_ptr& operator=(wx_ptr&) = delete;
42
43         wx_ptr(wx_ptr&& other)
44         {
45                 _wx = other._wx;
46                 other._wx = nullptr;
47         }
48
49         wx_ptr& operator=(wx_ptr&& other)
50         {
51                 if (this != &other) {
52                         _wx = other._wx;
53                         other._wx = nullptr;
54                 }
55                 return *this;
56         }
57
58         ~wx_ptr()
59         {
60                 if (_wx) {
61                         _wx->Destroy();
62                 }
63         }
64
65         wx_ptr& operator=(T* ptr)
66         {
67                 if (_wx) {
68                         _wx->Destroy();
69                 }
70                 _wx = ptr;
71                 return *this;
72         }
73
74         T* operator->()
75         {
76                 DCPOMATIC_ASSERT(_wx);
77                 return _wx;
78         }
79
80         operator bool() const
81         {
82                 return _wx != nullptr;
83         }
84
85         void reset()
86         {
87                 if (_wx) {
88                         _wx->Destroy();
89                         _wx = nullptr;
90                 }
91         }
92
93         template <typename... Args>
94         void reset(Args&&... args)
95         {
96                 if (_wx) {
97                         _wx->Destroy();
98                 }
99                 _wx = new T(std::forward<Args>(args)...);
100         }
101
102 private:
103         T* _wx = nullptr;
104 };
105
106
107
108 template <class T, typename... Args>
109 wx_ptr<T>
110 make_wx(Args... args)
111 {
112         return wx_ptr<T>(new T(std::forward<Args>(args)...));
113 }
114
115
116 #endif