1 /* 2 * Copyright (c) 2023 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 FOUNDATION_ACE_INTERFACES_INNER_API_ACE_KIT_INCLUDE_LIFECYCLE_CHECKABLE_H 17 #define FOUNDATION_ACE_INTERFACES_INNER_API_ACE_KIT_INCLUDE_LIFECYCLE_CHECKABLE_H 18 19 #include <atomic> 20 #include <cstdlib> 21 22 #include "ui/base/macros.h" 23 24 namespace OHOS::Ace { 25 class ACE_FORCE_EXPORT LifeCycleCheckable { 26 public: 27 template<class T> 28 class PtrHolder { 29 public: PtrHolder(T * ptr)30 PtrHolder(T* ptr) : ptr_(ptr) 31 { 32 ptr_->lastStack_ = &ptr; 33 ++ptr_->usingCount_; 34 } ~PtrHolder()35 ~PtrHolder() 36 { 37 --ptr_->usingCount_; 38 } 39 T* operator->() const 40 { 41 return ptr_; 42 } 43 44 void* operator new(size_t) = delete; 45 private: 46 T* ptr_; 47 }; 48 49 protected: ~LifeCycleCheckable()50 ~LifeCycleCheckable() 51 { 52 if (usingCount_) { 53 OnDetectedObjDestroyInUse(); 54 } 55 } 56 57 void OnDetectedObjDestroyInUse(); 58 59 private: 60 std::atomic_int usingCount_ = 0; 61 std::atomic<void*> lastStack_ = nullptr; 62 }; 63 } // namespace OHOS::Ace 64 65 #endif // FOUNDATION_ACE_INTERFACES_INNER_API_ACE_KIT_INCLUDE_LIFECYCLE_CHECKABLE_H 66