perkj | d027178 | 2016-10-20 07:24:01 | [diff] [blame] | 1 | /* |
| 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 | */ |
Henrik Kjellander | fb3e1b6 | 2017-06-29 06:03:04 | [diff] [blame] | 10 | #ifndef WEBRTC_RTC_BASE_REFCOUNTEDOBJECT_H_ |
| 11 | #define WEBRTC_RTC_BASE_REFCOUNTEDOBJECT_H_ |
perkj | d027178 | 2016-10-20 07:24:01 | [diff] [blame] | 12 | |
Henrik Kjellander | 88b2dd4 | 2017-06-29 05:52:50 | [diff] [blame] | 13 | #include <utility> |
perkj | d027178 | 2016-10-20 07:24:01 | [diff] [blame] | 14 | |
kjellander | 1979696 | 2017-06-30 17:45:21 | [diff] [blame] | 15 | #include "webrtc/rtc_base/atomicops.h" |
Henrik Kjellander | 88b2dd4 | 2017-06-29 05:52:50 | [diff] [blame] | 16 | |
| 17 | namespace rtc { |
| 18 | |
| 19 | template <class T> |
| 20 | class RefCountedObject : public T { |
| 21 | public: |
| 22 | RefCountedObject() {} |
| 23 | |
| 24 | template <class P0> |
| 25 | explicit RefCountedObject(P0&& p0) : T(std::forward<P0>(p0)) {} |
| 26 | |
| 27 | template <class P0, class P1, class... Args> |
| 28 | RefCountedObject(P0&& p0, P1&& p1, Args&&... args) |
| 29 | : T(std::forward<P0>(p0), |
| 30 | std::forward<P1>(p1), |
| 31 | std::forward<Args>(args)...) {} |
| 32 | |
| 33 | virtual int AddRef() const { return AtomicOps::Increment(&ref_count_); } |
| 34 | |
| 35 | virtual int Release() const { |
| 36 | int count = AtomicOps::Decrement(&ref_count_); |
| 37 | if (!count) { |
| 38 | delete this; |
| 39 | } |
| 40 | return count; |
| 41 | } |
| 42 | |
| 43 | // Return whether the reference count is one. If the reference count is used |
| 44 | // in the conventional way, a reference count of 1 implies that the current |
| 45 | // thread owns the reference and no other thread shares it. This call |
| 46 | // performs the test for a reference count of one, and performs the memory |
| 47 | // barrier needed for the owning thread to act on the object, knowing that it |
| 48 | // has exclusive access to the object. |
| 49 | virtual bool HasOneRef() const { |
| 50 | return AtomicOps::AcquireLoad(&ref_count_) == 1; |
| 51 | } |
| 52 | |
| 53 | protected: |
| 54 | virtual ~RefCountedObject() {} |
| 55 | |
| 56 | mutable volatile int ref_count_ = 0; |
| 57 | }; |
| 58 | |
| 59 | } // namespace rtc |
perkj | d027178 | 2016-10-20 07:24:01 | [diff] [blame] | 60 | |
Henrik Kjellander | fb3e1b6 | 2017-06-29 06:03:04 | [diff] [blame] | 61 | #endif // WEBRTC_RTC_BASE_REFCOUNTEDOBJECT_H_ |