1/* 2 * Copyright (c) 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 SYSTEM_WRAPPERS_INTERFACE_REF_COUNT_H_ 12#define SYSTEM_WRAPPERS_INTERFACE_REF_COUNT_H_ 13 14#include "system_wrappers/interface/atomic32_wrapper.h" 15 16namespace 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 43template <class T> 44class RefCountImpl : public T { 45 public: 46 RefCountImpl() : ref_count_(0) {} 47 48 template<typename P> 49 explicit RefCountImpl(P p) : T(p), ref_count_(0) {} 50 51 template<typename P1, typename P2> 52 RefCountImpl(P1 p1, P2 p2) : T(p1, p2), ref_count_(0) {} 53 54 template<typename P1, typename P2, typename 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> 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> 61 RefCountImpl(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) 62 : T(p1, p2, p3, p4, p5), ref_count_(0) {} 63 64 virtual int32_t AddRef() { 65 return ++ref_count_; 66 } 67 68 virtual int32_t Release() { 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 Atomic32Wrapper ref_count_; 78}; 79 80} // namespace webrtc 81 82#endif // SYSTEM_WRAPPERS_INTERFACE_REF_COUNT_H_ 83