Home | History | Annotate | Download | only in base
      1 /*
      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 
     18 namespace rtc {
     19 
     20 // Reference count interface.
     21 class RefCountInterface {
     22  public:
     23   virtual int AddRef() = 0;
     24   virtual int Release() = 0;
     25  protected:
     26   virtual ~RefCountInterface() {}
     27 };
     28 
     29 template <class T>
     30 class 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 
     69  protected:
     70   virtual ~RefCountedObject() {
     71   }
     72 
     73   int ref_count_;
     74 };
     75 
     76 }  // namespace rtc
     77 
     78 #endif  // TALK_APP_BASE_REFCOUNT_H_
     79