AWS IoT Device SDK C++ v2  1.33.0
AWS IoT Device SDK C++ v2
RefCounted.h
Go to the documentation of this file.
1 #pragma once
2 
7 #include <aws/common/assert.h>
8 #include <memory>
9 #include <mutex>
10 
11 namespace Aws
12 {
13  namespace Crt
14  {
28  template <class T> class RefCounted
29  {
30  protected:
33 
34  void AcquireRef()
35  {
36  m_mutex.lock();
37  if (m_count++ == 0)
38  {
39  m_strongPtr = static_cast<T *>(this)->shared_from_this();
40  }
41  m_mutex.unlock();
42  }
43 
44  void ReleaseRef()
45  {
46  // Move contents of m_strongPtr to a temp so that this
47  // object can't be destroyed until the function exits.
48  std::shared_ptr<T> tmpStrongPtr;
49 
50  m_mutex.lock();
51  AWS_ASSERT(m_count > 0 && "refcount has gone negative");
52  if (m_count-- == 1)
53  {
54  std::swap(m_strongPtr, tmpStrongPtr);
55  }
56  m_mutex.unlock();
57  }
58 
59  private:
60  RefCounted(const RefCounted &) = delete;
61  RefCounted &operator=(const RefCounted &) = delete;
62 
63  size_t m_count = 0;
64  std::shared_ptr<T> m_strongPtr;
65  std::mutex m_mutex;
66  };
67  } // namespace Crt
68 } // namespace Aws
Aws::Crt::RefCounted::AcquireRef
void AcquireRef()
Definition: RefCounted.h:34
Aws::Crt::RefCounted::~RefCounted
~RefCounted()
Definition: RefCounted.h:32
Aws::Crt::RefCounted::RefCounted
RefCounted()
Definition: RefCounted.h:31
Aws::Crt::RefCounted::ReleaseRef
void ReleaseRef()
Definition: RefCounted.h:44
Aws::Crt::RefCounted
Definition: RefCounted.h:29
Aws
Definition: Allocator.h:11