Agora Java API Reference for Android
AgoraRefCountedObject.h
1 
2 // Copyright (c) 2020 Agora.io. All rights reserved
3 
4 // This program is confidential and proprietary to Agora.io.
5 // And may not be copied, reproduced, modified, disclosed to others, published
6 // or used, in whole or in part, without the express prior written permission
7 // of Agora.io.
8 #pragma once
9 
10 #include "AgoraRefPtr.h"
11 #include "AgoraAtomicOps.h"
12 
13 namespace agora {
14 
15 class RefCounter {
16  public:
17  explicit RefCounter(int ref_count) : ref_count_(ref_count) {}
18 
19  void IncRef() { AtomicOps::Increment(&ref_count_); }
20 
25  agora::RefCountReleaseStatus DecRef() {
26  return (AtomicOps::Decrement(&ref_count_) == 0
27  ? agora::RefCountReleaseStatus::kDroppedLastRef
28  : agora::RefCountReleaseStatus::kOtherRefsRemained);
29  }
30 
39  bool HasOneRef() const { return (AtomicOps::AcquireLoad(&ref_count_) == 1); }
40 
41  private:
42  RefCounter();
43 
44  private:
45  volatile int ref_count_;
46 };
47 
55 template <class T>
56 class RefCountedObject : public T {
57  public:
58  RefCountedObject() {}
59 
60  template <class P0>
61  explicit RefCountedObject(P0&& p0) : T(std::forward<P0>(p0)) {}
62 
63  template <class P0, class P1, class... Args>
64  RefCountedObject(P0&& p0, P1&& p1, Args&&... args)
65  : T(std::forward<P0>(p0),
66  std::forward<P1>(p1),
67  std::forward<Args>(args)...) {}
68 
69  virtual void AddRef() const { ref_count_.IncRef(); }
70 
71  virtual agora::RefCountReleaseStatus Release() const {
72  const auto status = ref_count_.DecRef();
73  if (status == agora::RefCountReleaseStatus::kDroppedLastRef) {
74  delete this;
75  }
76  return status;
77  }
78 
87  virtual bool HasOneRef() const { return ref_count_.HasOneRef(); }
88 
89  protected:
90  virtual ~RefCountedObject() {}
91 
92  private:
93  RefCountedObject(const RefCountedObject&);
94  RefCountedObject& operator=(const RefCountedObject&);
95 
96  protected:
97  mutable agora::RefCounter ref_count_{0};
98 };
99 
100 template <typename T, typename... types>
101 inline agora_refptr<T> make_refptr(types&&... args) {
102  return agora_refptr<T>(new RefCountedObject<T>(std::forward<types>(args)...));
103 }
104 
105 } // namespace agora
agora::RefCountedObject::HasOneRef
virtual bool HasOneRef() const
Definition: AgoraRefCountedObject.h:87
agora::RefCountedObject
Definition: AgoraRefCountedObject.h:56
agora::RefCounter::HasOneRef
bool HasOneRef() const
Definition: AgoraRefCountedObject.h:39
agora::RefCounter
Definition: AgoraRefCountedObject.h:15
agora::RefCounter::DecRef
agora::RefCountReleaseStatus DecRef()
Definition: AgoraRefCountedObject.h:25