Line data Source code
1 : /*
2 : *
3 : * Copyright (c) 2020-2025 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 : template <typename T>
23 : class ReferenceCountedPtr;
24 :
25 : /** ReferenceCountedHandle acts like a shared_ptr to an object derived from ReferenceCounted. In contrast to shared_ptr, the handle
26 : * will always hold a valid target.
27 : * See also ReferenceCountedPtr for a nullable equivalent.
28 : */
29 : template <typename Target>
30 : class ReferenceCountedHandle
31 : {
32 : public:
33 546992 : explicit ReferenceCountedHandle(Target & target) : mTarget(target) { mTarget.Retain(); }
34 :
35 : // Ideally we would suppress this from within Optional.h, where this false positive is coming from. That said suppressing
36 : // here is okay since no other cases could create instance of ReferenceCountedHandle without going through explicit
37 : // contstructor.
38 : //
39 : // NOLINTNEXTLINE(clang-analyzer-core.CallAndMessage): Only in a false positive is mTarget uninitialized.
40 905962 : ~ReferenceCountedHandle() { mTarget.Release(); }
41 :
42 10638 : ReferenceCountedHandle(const ReferenceCountedHandle & that) : mTarget(that.mTarget) { mTarget.Retain(); }
43 :
44 348332 : ReferenceCountedHandle(ReferenceCountedHandle && that) : mTarget(that.mTarget) { mTarget.Retain(); }
45 :
46 : ReferenceCountedHandle & operator=(const ReferenceCountedHandle & that) = delete;
47 : ReferenceCountedHandle & operator=(ReferenceCountedHandle && that) = delete;
48 :
49 : bool operator==(const ReferenceCountedHandle & that) const { return &mTarget == &that.mTarget; }
50 : bool operator!=(const ReferenceCountedHandle & that) const { return !(*this == that); }
51 : bool operator==(const ReferenceCountedPtr<Target> & that) const { return that == &mTarget; }
52 : bool operator!=(const ReferenceCountedPtr<Target> & that) const { return that != &mTarget; }
53 :
54 828972 : Target * operator->() const { return &mTarget; }
55 259978 : Target & Get() const { return mTarget; }
56 :
57 : private:
58 : Target & mTarget;
59 : };
60 :
61 : } // namespace chip
|