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_FRAMEWORKS_BASE_UTILS_LIFECYCLE_CHECKABLE_H 17 #define FOUNDATION_ACE_FRAMEWORKS_BASE_UTILS_LIFECYCLE_CHECKABLE_H 18 19 #include <atomic> 20 #include <cstdlib> 21 #include "base/log/log.h" 22 23 namespace OHOS::Ace { 24 class LifeCycleCheckable { 25 public: 26 template<class T> 27 class PtrHolder { 28 public: PtrHolder(T * ptr)29 PtrHolder(T* ptr) : ptr_(ptr) 30 { 31 ++ptr_->usingCount_; 32 } ~PtrHolder()33 ~PtrHolder() 34 { 35 --ptr_->usingCount_; 36 } 37 T* operator->() const 38 { 39 return ptr_; 40 } 41 42 void* operator new(size_t) = delete; 43 private: 44 T* ptr_; 45 }; 46 47 protected: ~LifeCycleCheckable()48 ~LifeCycleCheckable() 49 { 50 if (usingCount_) { 51 LOGF("this object is still in use, use_count=%{public}d", usingCount_.load()); 52 abort(); 53 } 54 } 55 56 private: 57 std::atomic_int usingCount_ = 0; 58 }; 59 } // namespace OHOS::Ace 60 61 #endif // FOUNDATION_ACE_FRAMEWORKS_BASE_UTILS_LIFECYCLE_CHECKABLE_H 62