1/* 2 * Copyright (c) 2021 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 AIE_GUARD_H 17#define AIE_GUARD_H 18 19#include "utils/aie_macros.h" 20#include "utils/constants/constants.h" 21 22namespace OHOS { 23namespace AI { 24/** 25 * Delete the pointer which create with new T 26 * when the PointerGuard class is destructed. 27 */ 28template<class T> 29class PointerGuard { 30public: 31 explicit PointerGuard(T *&t) : t_(t), isValid_(true) {} 32 ~PointerGuard() 33 { 34 CHK_RET_NONE(t_ == nullptr || !isValid_); 35 AIE_DELETE(t_); 36 t_ = nullptr; 37 } 38 39 /** 40 * Detach the pointer guard. 41 */ 42 void Detach() 43 { 44 isValid_ = false; 45 } 46private: 47 T *&t_; 48 bool isValid_; 49}; 50 51/** 52 * Free the pointer which create with malloc when the MallocPointerGuard class is destructed. 53 */ 54template<class T> 55class MallocPointerGuard { 56public: 57 MallocPointerGuard() : t_(nullptr), isValid_(true) 58 {} 59 60 explicit MallocPointerGuard(T *t) : t_(t), isValid_(true) 61 {} 62 63 ~MallocPointerGuard() 64 { 65 CHK_RET_NONE(t_ == nullptr || !isValid_); 66 free(t_); 67 t_ = nullptr; 68 } 69 70 void setPointer(T *t) 71 { 72 t_ = t; 73 isValid_ = true; 74 } 75 /** 76 * Detach the pointer guard. 77 */ 78 void Detach() 79 { 80 isValid_ = false; 81 } 82 83private: 84 T *t_ = nullptr; 85 bool isValid_ = false; 86}; 87 88/** 89 * Delete the array pointer which create with new T[] when the ArrayPointerGuard class is destructed. 90 */ 91template<class T> 92class ArrayPointerGuard { 93public: 94 explicit ArrayPointerGuard(T *&t) : t_(t), isValid_(true) {} 95 ~ArrayPointerGuard() 96 { 97 CHK_RET_NONE(t_ == nullptr || !isValid_); 98 AIE_DELETE_ARRAY(t_); 99 t_ = nullptr; 100 } 101 102 /** 103 * Detach the array pointer guard. 104 */ 105 void Detach() 106 { 107 isValid_ = false; 108 } 109private: 110 T *&t_; 111 bool isValid_; 112}; 113 114/** 115 * The Destroy method of the T is used to delete T when the ResGuard class is destructed. 116 */ 117template<class T> 118class ResGuard { 119public: 120 explicit ResGuard(T *&t) : t_(t), isValid_(true) {} 121 ~ResGuard() 122 { 123 CHK_RET_NONE(t_ == nullptr || !isValid_); 124 T::Destroy(t_); 125 t_ = nullptr; 126 } 127 128 /** 129 * Detach the point guard. 130 */ 131 void Detach() 132 { 133 isValid_ = false; 134 } 135private: 136 T *&t_; 137 bool isValid_; 138}; 139} // namespace AI 140} // namespace OHOS 141 142#endif // AIE_GUARD_H