blob: eb097334f1be376b313ad56c6bd2722ae37e4cb5 [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
2 * Copyright 2011 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
11#ifndef TALK_APP_BASE_REFCOUNT_H_
12#define TALK_APP_BASE_REFCOUNT_H_
13
14#include <string.h>
15
16#include "webrtc/base/criticalsection.h"
17
18namespace rtc {
19
20// Reference count interface.
21class RefCountInterface {
22 public:
23 virtual int AddRef() = 0;
24 virtual int Release() = 0;
25 protected:
26 virtual ~RefCountInterface() {}
27};
28
29template <class T>
30class RefCountedObject : public T {
31 public:
32 RefCountedObject() : ref_count_(0) {
33 }
34
35 template<typename P>
36 explicit RefCountedObject(P p) : T(p), ref_count_(0) {
37 }
38
39 template<typename P1, typename P2>
40 RefCountedObject(P1 p1, P2 p2) : T(p1, p2), ref_count_(0) {
41 }
42
43 template<typename P1, typename P2, typename P3>
44 RefCountedObject(P1 p1, P2 p2, P3 p3) : T(p1, p2, p3), ref_count_(0) {
45 }
46
47 template<typename P1, typename P2, typename P3, typename P4>
48 RefCountedObject(P1 p1, P2 p2, P3 p3, P4 p4)
49 : T(p1, p2, p3, p4), ref_count_(0) {
50 }
51
52 template<typename P1, typename P2, typename P3, typename P4, typename P5>
53 RefCountedObject(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5)
54 : T(p1, p2, p3, p4, p5), ref_count_(0) {
55 }
56
57 virtual int AddRef() {
58 return rtc::AtomicOps::Increment(&ref_count_);
59 }
60
61 virtual int Release() {
62 int count = rtc::AtomicOps::Decrement(&ref_count_);
63 if (!count) {
64 delete this;
65 }
66 return count;
67 }
68
magjed@webrtc.orga43fce62015-02-21 13:23:27 +000069 // Return whether the reference count is one. If the reference count is used
70 // in the conventional way, a reference count of 1 implies that the current
71 // thread owns the reference and no other thread shares it. This call
72 // performs the test for a reference count of one, and performs the memory
73 // barrier needed for the owning thread to act on the object, knowing that it
74 // has exclusive access to the object.
75 virtual bool HasOneRef() const {
76 return rtc::AtomicOps::Load(&ref_count_) == 1;
77 }
78
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000079 protected:
80 virtual ~RefCountedObject() {
81 }
82
magjed@webrtc.orga43fce62015-02-21 13:23:27 +000083 volatile int ref_count_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000084};
85
86} // namespace rtc
87
88#endif // TALK_APP_BASE_REFCOUNT_H_