1 /*
2  *  Copyright (c) 2012 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 SYSTEM_WRAPPERS_INCLUDE_REF_COUNT_H_
12 #define SYSTEM_WRAPPERS_INCLUDE_REF_COUNT_H_
13 
14 #include "webrtc/system_wrappers/include/atomic32.h"
15 
16 namespace webrtc {
17 
18 // This class can be used for instantiating
19 // reference counted objects.
20 // int32_t AddRef() and int32_t Release().
21 // Usage:
22 // RefCountImpl<T>* implementation = new RefCountImpl<T>(p);
23 //
24 // Example:
25 // class MyInterface {
26 //  public:
27 //   virtual void DoSomething() = 0;
28 //   virtual int32_t AddRef() = 0;
29 //   virtual int32_t Release() = 0:
30 //  private:
31 //   virtual ~MyInterface(){};
32 // }
33 // class MyImplementation : public MyInterface {
34 //  public:
35 //   virtual DoSomething() { printf("hello"); };
36 // };
37 // MyImplementation* CreateMyImplementation() {
38 //   RefCountImpl<MyImplementation>* implementation =
39 //       new RefCountImpl<MyImplementation>();
40 //   return implementation;
41 // }
42 
43 template <class T>
44 class RefCountImpl : public T {
45  public:
RefCountImpl()46   RefCountImpl() : ref_count_(0) {}
47 
48   template<typename P>
RefCountImpl(P p)49   explicit RefCountImpl(P p) : T(p), ref_count_(0) {}
50 
51   template<typename P1, typename P2>
RefCountImpl(P1 p1,P2 p2)52   RefCountImpl(P1 p1, P2 p2) : T(p1, p2), ref_count_(0) {}
53 
54   template<typename P1, typename P2, typename P3>
RefCountImpl(P1 p1,P2 p2,P3 p3)55   RefCountImpl(P1 p1, P2 p2, P3 p3) : T(p1, p2, p3), ref_count_(0) {}
56 
57   template<typename P1, typename P2, typename P3, typename P4>
RefCountImpl(P1 p1,P2 p2,P3 p3,P4 p4)58   RefCountImpl(P1 p1, P2 p2, P3 p3, P4 p4) : T(p1, p2, p3, p4), ref_count_(0) {}
59 
60   template<typename P1, typename P2, typename P3, typename P4, typename P5>
RefCountImpl(P1 p1,P2 p2,P3 p3,P4 p4,P5 p5)61   RefCountImpl(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5)
62       : T(p1, p2, p3, p4, p5), ref_count_(0) {}
63 
AddRef()64   int32_t AddRef() const override {
65     return ++ref_count_;
66   }
67 
Release()68   int32_t Release() const override {
69     int32_t ref_count;
70     ref_count = --ref_count_;
71     if (ref_count == 0)
72       delete this;
73     return ref_count;
74   }
75 
76  protected:
77   mutable Atomic32 ref_count_;
78 };
79 
80 }  // namespace webrtc
81 
82 #endif  // SYSTEM_WRAPPERS_INCLUDE_REF_COUNT_H_
83