1 /*
2  * Copyright (c) 2020 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 OHOS_UPTR_H
17 #define OHOS_UPTR_H
18 
19 namespace OHOS {
20 template<typename T>
21 struct RemoveRef {
22     typedef T type;
23 };
24 
25 template<class T>
26 struct RemoveRef<T &> {
27     typedef T type;
28 };
29 
30 template<class T>
31 struct RemoveRef<T &&> {
32     typedef T type;
33 };
34 
35 template<typename T>
36 typename RemoveRef<T>::type &&Move(T &&t)
37 {
38     using Rtype = typename RemoveRef<T>::type &&;
39     return static_cast<Rtype>(t);
40 }
41 
42 template<typename T>
43 class Uptr {
44 public:
45     explicit Uptr(T *p = nullptr) : ptr_(p)
46     {
47     }
48 
49     ~Uptr()
50     {
51         delete ptr_;
52     }
53 
54     Uptr(Uptr &&ptr) : ptr_(ptr.ptr_)
55     {
56         ptr.ptr_ = nullptr;
57     }
58 
59     void reset(T *p = nullptr)
60     {
61         if (p != ptr_) {
62             delete ptr_;
63             ptr_ = p;
64         }
65     }
66 
67     T &operator*() const
68     {
69         return *ptr_;
70     }
71 
72     T *operator->() const
73     {
74         return ptr_;
75     }
76 
77     T *get() const
78     {
79         return ptr_;
80     }
81 
82     bool operator==(T *p) const
83     {
84         return ptr_ == p;
85     }
86 
87     bool operator!=(T *p) const
88     {
89         return ptr_ != p;
90     }
91 
92     void swap(Uptr &p2)
93     {
94         T* tmp = ptr_;
95         ptr_ = p2.ptr_;
96         p2.ptr_ = tmp;
97     }
98 
99     T *release()
100     {
101         T *retVal = ptr_;
102         ptr_ = nullptr;
103         return retVal;
104     }
105 
106 private:
107     T *ptr_ = nullptr;
108 
109     template<class T2> bool operator==(Uptr<T2> const &p2) const;
110     template<class T2> bool operator!=(Uptr<T2> const &p2) const;
111 
112     Uptr(const Uptr &);
113     void operator=(const Uptr&);
114 };
115 }  // namespace OHOS
116 #endif  // OHOS_UPTR_H