Zang MingJie | 32c1393 | 2021-07-20 22:18:50 +0800 | [diff] [blame] | 1 | /* |
| 2 | * |
| 3 | * Copyright (c) 2020-2021 Project CHIP Authors |
| 4 | * |
| 5 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | * you may not use this file except in compliance with the License. |
| 7 | * You may obtain a copy of the License at |
| 8 | * |
| 9 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | * |
| 11 | * Unless required by applicable law or agreed to in writing, software |
| 12 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | * See the License for the specific language governing permissions and |
| 15 | * limitations under the License. |
| 16 | */ |
| 17 | |
| 18 | #pragma once |
| 19 | |
| 20 | namespace chip { |
| 21 | |
| 22 | /** ReferenceCountedHandle acts like a shared_ptr to an object derived from ReferenceCounted. In contrast to shared_ptr, the handle |
| 23 | * will always hold a valid target */ |
| 24 | template <typename Target> |
| 25 | class ReferenceCountedHandle |
| 26 | { |
| 27 | public: |
| 28 | explicit ReferenceCountedHandle(Target & target) : mTarget(target) { mTarget.Retain(); } |
| 29 | ~ReferenceCountedHandle() { mTarget.Release(); } |
| 30 | |
Zang MingJie | 102c6e2 | 2021-09-14 21:08:41 +0800 | [diff] [blame] | 31 | ReferenceCountedHandle(const ReferenceCountedHandle & that) : mTarget(that.mTarget) { mTarget.Retain(); } |
| 32 | |
| 33 | ReferenceCountedHandle(ReferenceCountedHandle && that) : mTarget(that.mTarget) { mTarget.Retain(); } |
| 34 | |
Zang MingJie | 32c1393 | 2021-07-20 22:18:50 +0800 | [diff] [blame] | 35 | ReferenceCountedHandle & operator=(const ReferenceCountedHandle & that) = delete; |
Zang MingJie | 32c1393 | 2021-07-20 22:18:50 +0800 | [diff] [blame] | 36 | ReferenceCountedHandle & operator=(ReferenceCountedHandle && that) = delete; |
| 37 | |
| 38 | bool operator==(const ReferenceCountedHandle & that) const { return &mTarget == &that.mTarget; } |
| 39 | bool operator!=(const ReferenceCountedHandle & that) const { return !(*this == that); } |
| 40 | |
Zang MingJie | 7a4028d | 2022-01-08 03:00:35 +0800 | [diff] [blame] | 41 | Target * operator->() const { return &mTarget; } |
Zang MingJie | 102c6e2 | 2021-09-14 21:08:41 +0800 | [diff] [blame] | 42 | Target & Get() const { return mTarget; } |
| 43 | |
Zang MingJie | 32c1393 | 2021-07-20 22:18:50 +0800 | [diff] [blame] | 44 | private: |
| 45 | Target & mTarget; |
| 46 | }; |
| 47 | |
| 48 | } // namespace chip |