From 17a4ca570582605d0977fae4cfad051240cfaf5f Mon Sep 17 00:00:00 2001 From: Caoruihong Date: Tue, 12 Sep 2023 00:49:51 +0800 Subject: [PATCH] feat: add lifecycle check for all RefPtr of ace types Signed-off-by: Caoruihong --- frameworks/base/memory/referenced.h | 5 +- frameworks/base/utils/lifecycle_checkable.h | 61 +++++++++++++++++++++ 2 files changed, 64 insertions(+), 2 deletions(-) create mode 100644 frameworks/base/utils/lifecycle_checkable.h diff --git a/frameworks/base/memory/referenced.h b/frameworks/base/memory/referenced.h index 83dfc6e3324..e17b99dbf90 100644 --- a/frameworks/base/memory/referenced.h +++ b/frameworks/base/memory/referenced.h @@ -21,6 +21,7 @@ #include "base/memory/memory_monitor.h" #include "base/memory/ref_counter.h" #include "base/utils/macros.h" +#include "base/utils/lifecycle_checkable.h" #define ACE_REMOVE(...) @@ -32,7 +33,7 @@ template class WeakPtr; // Inherit this class to use 'RefPtr' and 'WeakPtr' to manage pointer of instance. -class Referenced { +class Referenced : public LifeCycleCheckable { public: // Use raw pointer to construct 'RefPtr' and 'WeakPtr'. template @@ -166,7 +167,7 @@ public: Swap(RefPtr()); } - T* operator->() const + typename LifeCycleCheckable::PtrHolder operator->() const { return rawPtr_; } diff --git a/frameworks/base/utils/lifecycle_checkable.h b/frameworks/base/utils/lifecycle_checkable.h new file mode 100644 index 00000000000..1463db315a8 --- /dev/null +++ b/frameworks/base/utils/lifecycle_checkable.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_ACE_FRAMEWORKS_BASE_UTILS_LIFECYCLE_CHECKABLE_H +#define FOUNDATION_ACE_FRAMEWORKS_BASE_UTILS_LIFECYCLE_CHECKABLE_H + +#include +#include +#include "base/log/log.h" + +namespace OHOS::Ace { +class LifeCycleCheckable { +public: + template + class PtrHolder { + public: + PtrHolder(T* ptr) : ptr_(ptr) + { + ++ptr_->usingCount_; + } + ~PtrHolder() + { + --ptr_->usingCount_; + } + T* operator->() const + { + return ptr_; + } + + void* operator new(size_t) = delete; + private: + T* ptr_; + }; + +protected: + ~LifeCycleCheckable() + { + if (usingCount_) { + LOGF("this object is still in use, use_count=%{public}d", usingCount_.load()); + abort(); + } + } + +private: + std::atomic_int usingCount_ = 0; +}; +} // namespace OHOS::Ace + +#endif // FOUNDATION_ACE_FRAMEWORKS_BASE_UTILS_LIFECYCLE_CHECKABLE_H -- Gitee