Line data Source code
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 28119 : explicit ReferenceCountedHandle(Target & target) : mTarget(target) { mTarget.Retain(); }
29 :
30 : // Ideally we would suppress this from within Optional.h, where this false positive is coming from. That said suppressing
31 : // here is okay since no other cases could create instance of ReferenceCountedHandle without going through explicit
32 : // contstructor.
33 : //
34 : // NOLINTNEXTLINE(clang-analyzer-core.CallAndMessage): Only in a false positive is mTarget uninitialized.
35 27690 : ~ReferenceCountedHandle() { mTarget.Release(); }
36 :
37 8669 : ReferenceCountedHandle(const ReferenceCountedHandle & that) : mTarget(that.mTarget) { mTarget.Retain(); }
38 :
39 9863 : ReferenceCountedHandle(ReferenceCountedHandle && that) : mTarget(that.mTarget) { mTarget.Retain(); }
40 :
41 : ReferenceCountedHandle & operator=(const ReferenceCountedHandle & that) = delete;
42 : ReferenceCountedHandle & operator=(ReferenceCountedHandle && that) = delete;
43 :
44 : bool operator==(const ReferenceCountedHandle & that) const { return &mTarget == &that.mTarget; }
45 : bool operator!=(const ReferenceCountedHandle & that) const { return !(*this == that); }
46 :
47 133361 : Target * operator->() const { return &mTarget; }
48 40686 : Target & Get() const { return mTarget; }
49 :
50 : private:
51 : Target & mTarget;
52 : };
53 :
54 : } // namespace chip
|