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>
21 #if defined(ZCPOINTER_TRACK_REFS) && ZCPOINTER_TRACK_REFS
23 template <typename T
> class ref
;
28 class OwnedPtrDeleter
{
33 OwnedPtrDeleter(OwnedPtrDeleter
&& other
) : refs_(std
::move(other
.refs_
)) {
36 void operator()(T
* t
) const {
37 for (auto& ref
: refs_
) {
46 void AddRef(ref
<T
>* ref
) {
47 refs_
.push_front(ref
);
50 void RemoveRef(ref
<T
>* ref
) {
55 std
::forward_list
<ref
<T
>*> refs_
;
58 void RaiseUseAfterFree(const char* error
) __attribute__((noreturn
));
60 } // namespace internal
63 class owned
: public std
::unique_ptr
<T
, internal
::OwnedPtrDeleter
<T
>> {
65 using Deleter
= internal
::OwnedPtrDeleter
<T
>;
68 using std
::unique_ptr
<T
, Deleter
>::unique_ptr
;
77 T
* GetRawPointer() const {
83 return this->std
::unique_ptr
<T
, Deleter
>::get();
90 ref() : ptr_(DeletedSentinel()) {}
92 explicit ref(owned
<T
>& o
) : ptr_(&o
) {
93 ptr_
->get_deleter().AddRef(this);
96 ref(const ref
<T
>& o
) {
100 ref
<T
>& operator=(const ref
<T
>& o
) {
103 ptr_
->get_deleter().AddRef(this);
109 ptr_
->get_deleter().RemoveRef(this);
113 T
* operator->() const {
115 return ptr_
->GetRawPointer();
119 friend class internal
::OwnedPtrDeleter
<T
>;
122 ptr_
= DeletedSentinel();
126 void CheckDeleted() const {
128 internal
::RaiseUseAfterFree("attempt to access deleted pointer");
132 bool IsDeleted() const {
133 return ptr_
== DeletedSentinel();
136 inline static owned
<T
>* DeletedSentinel() {
137 return reinterpret_cast<owned
<T
>*>(std
::numeric_limits
<uintptr_t>::max());
145 template <typename T
>
146 using owned
= std
::unique_ptr
<T
>;
148 template <typename T
>