staticlib_support
1.2.1
Main Page
Modules
Namespaces
Classes
Files
File List
File Members
All
Classes
Namespaces
Files
Functions
Variables
Typedefs
Enumerations
Enumerator
Macros
Groups
staticlib
support
observer_ptr.hpp
Go to the documentation of this file.
1
/*
2
* Copyright 2017, alex at staticlibs.net
3
*
4
* Licensed under the Apache License, Version 2.0 (the "License");
5
* you may not use this file except in compliance with the License.
6
* You may obtain a copy of the License at
7
*
8
* http://www.apache.org/licenses/LICENSE-2.0
9
*
10
* Unless required by applicable law or agreed to in writing, software
11
* distributed under the License is distributed on an "AS IS" BASIS,
12
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
* See the License for the specific language governing permissions and
14
* limitations under the License.
15
*/
16
17
/*
18
* File: observer_ptr.hpp
19
* Author: alex
20
*
21
* Created on February 4, 2017, 9:01 PM
22
*/
23
24
#ifndef STATICLIB_SUPPORT_OBSERVER_PTR_HPP
25
#define STATICLIB_SUPPORT_OBSERVER_PTR_HPP
26
27
#include "
staticlib/support/exception.hpp
"
28
29
namespace
staticlib {
30
namespace
support {
31
35
class
bad_observed_pointer_access_exception
:
public
exception
{
36
public
:
37
41
bad_observed_pointer_access_exception
() :
42
exception
(
"Invalid attempt to access empty observed pointer"
) { }
43
};
44
45
49
template
<
typename
T>
50
class
observer_ptr
{
54
T* target =
nullptr
;
55
56
public
:
60
observer_ptr
() { }
61
67
explicit
observer_ptr
(T* target) :
68
target(target) { }
69
75
explicit
observer_ptr
(T& target) :
76
target(std::addressof(target)) { }
77
83
observer_ptr
(
const
observer_ptr
& other) :
84
target(other.target) { }
85
92
observer_ptr
&
operator=
(
const
observer_ptr
& other) {
93
target = other.target;
94
return
*
this
;
95
};
96
102
explicit
operator
bool()
const
{
103
return
has_value
();
104
}
105
111
bool
has_value
()
const
{
112
return
nullptr
!= target;
113
}
114
121
T&
operator*
()
const
{
122
if
(
has_value
()) {
123
return
*target;
124
}
else
{
125
throw
bad_observed_pointer_access_exception
();
126
}
127
}
128
135
T*
operator->
()
const
{
136
if
(
has_value
()) {
137
return
target;
138
}
else
{
139
throw
bad_observed_pointer_access_exception
();
140
}
141
}
142
149
T*
get
()
const
{
150
if
(
has_value
()) {
151
return
target;
152
}
else
{
153
throw
bad_observed_pointer_access_exception
();
154
}
155
}
156
160
void
reset
(T* targ =
nullptr
) {
161
target = targ;
162
}
163
};
164
165
172
template
<
typename
T>
173
observer_ptr<T>
make_observer_ptr
(T* target) {
174
return
observer_ptr<T>
(target);
175
}
176
183
template
<
typename
T>
184
observer_ptr<T>
make_observer_ptr
(T& target) {
185
return
observer_ptr<T>
(target);
186
}
187
188
}
// namespace
189
}
190
191
#endif
/* STATICLIB_SUPPORT_OBSERVER_PTR_HPP */
192
Generated on Thu Apr 4 2019 22:52:24 for staticlib_support by
1.8.1.2