blob: 2a54e17b3c9ba2cab0ecf5c3c87555a5b77e1746 [file] [log] [blame]
Zang MingJie32c13932021-07-20 22:18:50 +08001/*
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
20namespace 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 */
24template <typename Target>
25class ReferenceCountedHandle
26{
27public:
28 explicit ReferenceCountedHandle(Target & target) : mTarget(target) { mTarget.Retain(); }
29 ~ReferenceCountedHandle() { mTarget.Release(); }
30
Zang MingJie102c6e22021-09-14 21:08:41 +080031 ReferenceCountedHandle(const ReferenceCountedHandle & that) : mTarget(that.mTarget) { mTarget.Retain(); }
32
33 ReferenceCountedHandle(ReferenceCountedHandle && that) : mTarget(that.mTarget) { mTarget.Retain(); }
34
Zang MingJie32c13932021-07-20 22:18:50 +080035 ReferenceCountedHandle & operator=(const ReferenceCountedHandle & that) = delete;
Zang MingJie32c13932021-07-20 22:18:50 +080036 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 MingJie7a4028d2022-01-08 03:00:35 +080041 Target * operator->() const { return &mTarget; }
Zang MingJie102c6e22021-09-14 21:08:41 +080042 Target & Get() const { return mTarget; }
43
Zang MingJie32c13932021-07-20 22:18:50 +080044private:
45 Target & mTarget;
46};
47
48} // namespace chip