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()(T
* t
) const {
43 for (auto& ref
: refs_
) {
52 void AddRef(ref
<T
>* ref
) {
53 refs_
.push_front(ref
);
56 void RemoveRef(ref
<T
>* ref
) {
61 std
::forward_list
<ref
<T
>*> refs_
;
64 void RaiseUseAfterFree(const char* error
) __attribute__((noreturn
));
66 } // namespace internal
69 class owned
: public std
::unique_ptr
<T
, internal
::OwnedPtrDeleter
<T
>> {
71 using Deleter
= internal
::OwnedPtrDeleter
<T
>;
74 using std
::unique_ptr
<T
, Deleter
>::unique_ptr
;
82 return this->std
::unique_ptr
<T
, Deleter
>::get();
89 ref() : ptr_(DeletedSentinel()) {}
91 explicit ref(owned
<T
>& o
) : ptr_(&o
) {
92 ptr_
->get_deleter().AddRef(this);
95 ref(const ref
<T
>& o
) {
99 ref
<T
>& operator=(const ref
<T
>& o
) {
102 ptr_
->get_deleter().AddRef(this);
109 ptr_
->get_deleter().RemoveRef(this);
114 T
* operator->() const {
116 return ptr_
->operator->();
120 friend class internal
::OwnedPtrDeleter
<T
>;
123 ptr_
= DeletedSentinel();
127 void CheckDeleted() const {
129 internal
::RaiseUseAfterFree("attempt to access deleted pointer");
133 bool IsDeleted() const {
134 return ptr_
== DeletedSentinel();
137 inline static owned
<T
>* DeletedSentinel() {
138 return reinterpret_cast<owned
<T
>*>(std
::numeric_limits
<uintptr_t>::max());
146 template <typename T
>
147 using owned
= std
::unique_ptr
<T
>;
149 template <typename T
>