1 // Copyright 2016 Google Inc. All rights reserved.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
17 #include <forward_list>
22 class UseAfterFreeError
: public std
::logic_error
{
24 using std
::logic_error
::logic_error
;
27 #if defined(ZCPOINTER_TRACK_REFS) && ZCPOINTER_TRACK_REFS
29 template <typename T
> class ref
;
34 class OwnedPtrDeleter
{
39 OwnedPtrDeleter(OwnedPtrDeleter
&& other
) : refs_(std
::move(other
.refs_
)) {
42 void operator=(const OwnedPtrDeleter
& o
) {
46 void operator()(T
* t
) const {
47 for (auto& ref
: refs_
) {
56 void AddRef(ref
<T
>* ref
) {
57 refs_
.push_front(ref
);
60 void RemoveRef(ref
<T
>* ref
) {
65 std
::forward_list
<ref
<T
>*> refs_
;
68 void RaiseUseAfterFree(const char* error
) __attribute__((noreturn
));
70 } // namespace internal
73 class owned
: public std
::unique_ptr
<T
, internal
::OwnedPtrDeleter
<T
>> {
75 using Deleter
= internal
::OwnedPtrDeleter
<T
>;
78 using std
::unique_ptr
<T
, Deleter
>::unique_ptr
;
86 return this->std
::unique_ptr
<T
, Deleter
>::get();
93 ref() : ptr_(nullptr) {}
95 ref(std
::nullptr_t
) : ref() {}
97 explicit ref(owned
<T
>& o
) : ptr_(nullptr) {
100 ptr_
->get_deleter().AddRef(this);
104 ref(const ref
<T
>& r
) {
108 ref
<T
>& operator=(const ref
<T
>& o
) {
110 if (ptr_
!= nullptr && !IsDeleted()) {
111 ptr_
->get_deleter().AddRef(this);
117 if (ptr_
!= nullptr && !IsDeleted()) {
118 ptr_
->get_deleter().RemoveRef(this);
123 T
* operator->() const {
125 return ptr_
->operator->();
128 bool operator==(const ref
<T
>& r
) const {
129 if (ptr_
== nullptr) {
130 return r
.ptr_
== nullptr;
132 return ptr_
== r
.ptr_
&& *ptr_
== *r
.ptr_
;
136 bool operator==(std
::nullptr_t
) const {
137 return ptr_
== nullptr;
140 bool operator!=(const ref
<T
>& r
) const {
141 return !(*this == r
);
145 friend class internal
::OwnedPtrDeleter
<T
>;
148 ptr_
= DeletedSentinel();
152 void CheckDeleted() const {
154 internal
::RaiseUseAfterFree("attempt to access deleted pointer");
158 bool IsDeleted() const {
159 return ptr_
== DeletedSentinel();
162 inline static owned
<T
>* DeletedSentinel() {
163 return reinterpret_cast<owned
<T
>*>(std
::numeric_limits
<uintptr_t>::max());
171 template <typename T
>
172 using owned
= std
::unique_ptr
<T
>;
174 template <typename T
>