1 /*
2  * Copyright (c) 2024 Huawei Device Co., Ltd.
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
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
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.
14  */
15 
16 #ifndef ARK_WEB_SCOPED_REFPTR_H_
17 #define ARK_WEB_SCOPED_REFPTR_H_
18 
19 template<class T>
20 class ark_web_scoped_refptr {
21 public:
22     ark_web_scoped_refptr() = default;
23 
ark_web_scoped_refptr(T * p)24     ark_web_scoped_refptr(T* p) : ptr_(p)
25     {
26         if (ptr_) {
27             ptr_->IncreRef();
28         }
29     }
30 
ark_web_scoped_refptr(const ark_web_scoped_refptr & r)31     ark_web_scoped_refptr(const ark_web_scoped_refptr& r) : ark_web_scoped_refptr(r.ptr_) {}
32 
~ark_web_scoped_refptr()33     ~ark_web_scoped_refptr()
34     {
35         if (ptr_) {
36             ptr_->DecreRef();
37         }
38     }
39 
get()40     T* get() const
41     {
42         return ptr_;
43     }
44 
45     T* operator->() const
46     {
47         return ptr_;
48     }
49 
50     explicit operator bool() const
51     {
52         return ptr_ != nullptr;
53     }
54 
55     ark_web_scoped_refptr& operator=(std::nullptr_t)
56     {
57         return *this;
58     }
59 
60     ark_web_scoped_refptr& operator=(T* p)
61     {
62         return *this = ark_web_scoped_refptr(p);
63     }
64 
65     ark_web_scoped_refptr& operator=(ark_web_scoped_refptr r) noexcept
66     {
67         std::swap(ptr_, r.ptr_);
68         return *this;
69     }
70 
71 private:
72     T* ptr_ = nullptr;
73 };
74 
75 #endif // ARK_WEB_SCOPED_REFPTR_H_
76