ref_counted_object.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * Copyright 2016 The WebRTC Project Authors. All rights reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #ifndef RTC_BASE_REF_COUNTED_OBJECT_H_
  11. #define RTC_BASE_REF_COUNTED_OBJECT_H_
  12. #include <type_traits>
  13. #include <utility>
  14. #include "rtc_base/constructor_magic.h"
  15. #include "rtc_base/ref_count.h"
  16. #include "rtc_base/ref_counter.h"
  17. namespace rtc {
  18. template <class T>
  19. class RefCountedObject : public T {
  20. public:
  21. RefCountedObject() {}
  22. template <class P0>
  23. explicit RefCountedObject(P0&& p0) : T(std::forward<P0>(p0)) {}
  24. template <class P0, class P1, class... Args>
  25. RefCountedObject(P0&& p0, P1&& p1, Args&&... args)
  26. : T(std::forward<P0>(p0),
  27. std::forward<P1>(p1),
  28. std::forward<Args>(args)...) {}
  29. virtual void AddRef() const { ref_count_.IncRef(); }
  30. virtual RefCountReleaseStatus Release() const {
  31. const auto status = ref_count_.DecRef();
  32. if (status == RefCountReleaseStatus::kDroppedLastRef) {
  33. delete this;
  34. }
  35. return status;
  36. }
  37. // Return whether the reference count is one. If the reference count is used
  38. // in the conventional way, a reference count of 1 implies that the current
  39. // thread owns the reference and no other thread shares it. This call
  40. // performs the test for a reference count of one, and performs the memory
  41. // barrier needed for the owning thread to act on the object, knowing that it
  42. // has exclusive access to the object.
  43. virtual bool HasOneRef() const { return ref_count_.HasOneRef(); }
  44. protected:
  45. virtual ~RefCountedObject() {}
  46. mutable webrtc::webrtc_impl::RefCounter ref_count_{0};
  47. RTC_DISALLOW_COPY_AND_ASSIGN(RefCountedObject);
  48. };
  49. } // namespace rtc
  50. #endif // RTC_BASE_REF_COUNTED_OBJECT_H_