Roc Toolkit internal modules
Roc Toolkit: real-time audio streaming
Loading...
Searching...
No Matches
refcnt.h
Go to the documentation of this file.
1/*
2 * Copyright (c) 2015 Roc authors
3 *
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
7 */
8
9//! @file roc_core/refcnt.h
10//! @brief Base class for reference countable objects.
11
12#ifndef ROC_CORE_REFCNT_H_
13#define ROC_CORE_REFCNT_H_
14
15#include "roc_core/atomic.h"
17#include "roc_core/panic.h"
18
19namespace roc {
20namespace core {
21
22//! Base class for reference countable objects.
23//!
24//! @tparam T defines the derived class, which should provide free() method.
25template <class T> class RefCnt : public NonCopyable<RefCnt<T> > {
26public:
27 RefCnt()
28 : counter_(0) {
29 }
30
31 ~RefCnt() {
32 if (counter_ != 0) {
33 roc_panic("refcnt: reference counter is non-zero in destructor, counter=%d",
34 (int)counter_);
35 }
36 }
37
38 //! Get reference counter.
39 long getref() const {
40 return counter_;
41 }
42
43 //! Increment reference counter.
44 void incref() const {
45 if (counter_ < 0) {
46 roc_panic("refcnt: attempting to call incref() on freed object");
47 }
48 ++counter_;
49 }
50
51 //! Decrement reference counter.
52 //! @remarks
53 //! Calls free() if reference counter becomes zero.
54 void decref() const {
55 if (counter_ <= 0) {
56 roc_panic("refcnt: attempting to call decref() on destroyed object");
57 }
58 if (--counter_ == 0) {
59 static_cast<T*>(const_cast<RefCnt*>(this))->destroy();
60 }
61 }
62
63private:
64 mutable Atomic counter_;
65};
66
67} // namespace core
68} // namespace roc
69
70#endif // ROC_CORE_REFCNT_H_
Atomic integer.
Atomic integer.
Definition: atomic.h:21
Base class for non-copyable objects.
Definition: noncopyable.h:23
Base class for reference countable objects.
Definition: refcnt.h:25
long getref() const
Get reference counter.
Definition: refcnt.h:39
void incref() const
Increment reference counter.
Definition: refcnt.h:44
void decref() const
Decrement reference counter.
Definition: refcnt.h:54
Root namespace.
Non-copyable object.
Panic function.
#define roc_panic(...)
Print error message and terminate program gracefully.
Definition: panic.h:42