blob: f04b7f974cfeec2dafcda7a4160ef0117eedfa1d [file] [log] [blame]
perkj0489e492016-10-20 00:24:01 -07001/*
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 */
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020010#ifndef RTC_BASE_REFCOUNTEDOBJECT_H_
11#define RTC_BASE_REFCOUNTEDOBJECT_H_
perkj0489e492016-10-20 00:24:01 -070012
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020013#include <utility>
perkj0489e492016-10-20 00:24:01 -070014
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020015#include "rtc_base/atomicops.h"
Niels Möller6f72f562017-10-19 13:15:17 +020016#include "rtc_base/refcount.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020017
18namespace rtc {
19
20template <class T>
21class RefCountedObject : public T {
22 public:
23 RefCountedObject() {}
24
25 template <class P0>
26 explicit RefCountedObject(P0&& p0) : T(std::forward<P0>(p0)) {}
27
28 template <class P0, class P1, class... Args>
29 RefCountedObject(P0&& p0, P1&& p1, Args&&... args)
30 : T(std::forward<P0>(p0),
31 std::forward<P1>(p1),
32 std::forward<Args>(args)...) {}
33
Niels Möller6f72f562017-10-19 13:15:17 +020034 virtual void AddRef() const { AtomicOps::Increment(&ref_count_); }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020035
Niels Möller6f72f562017-10-19 13:15:17 +020036 virtual RefCountReleaseStatus Release() const {
37 if (AtomicOps::Decrement(&ref_count_) == 0) {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020038 delete this;
Niels Möller6f72f562017-10-19 13:15:17 +020039 return RefCountReleaseStatus::kDroppedLastRef;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020040 }
Niels Möller6f72f562017-10-19 13:15:17 +020041 return RefCountReleaseStatus::kOtherRefsRemained;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020042 }
43
44 // Return whether the reference count is one. If the reference count is used
45 // in the conventional way, a reference count of 1 implies that the current
46 // thread owns the reference and no other thread shares it. This call
47 // performs the test for a reference count of one, and performs the memory
48 // barrier needed for the owning thread to act on the object, knowing that it
49 // has exclusive access to the object.
50 virtual bool HasOneRef() const {
51 return AtomicOps::AcquireLoad(&ref_count_) == 1;
52 }
53
54 protected:
55 virtual ~RefCountedObject() {}
56
57 mutable volatile int ref_count_ = 0;
58};
59
60} // namespace rtc
perkj0489e492016-10-20 00:24:01 -070061
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020062#endif // RTC_BASE_REFCOUNTEDOBJECT_H_