cesium-native 0.43.0
Loading...
Searching...
No Matches
ReferenceCounted.h
1#pragma once
2
3#include <CesiumUtility/Assert.h>
4
5#include <atomic>
6#include <cstdint>
7
8#ifndef NDEBUG
9#include <thread>
10#endif
11
12namespace CesiumUtility {
13
15#ifndef NDEBUG
16template <bool isThreadSafe> class ThreadIdHolder;
17
18template <> class ThreadIdHolder<false> {
19 ThreadIdHolder() : _threadID(std::this_thread::get_id()) {}
20
21 std::thread::id _threadID;
22
23 template <typename T, bool isThreadSafe> friend class ReferenceCounted;
24};
25
26template <> class ThreadIdHolder<true> {};
27#endif
49template <typename T, bool isThreadSafe = true>
51#ifndef NDEBUG
52 : public ThreadIdHolder<isThreadSafe>
53#endif
54{
55public:
56 ReferenceCounted() noexcept {}
57 ~ReferenceCounted() noexcept { CESIUM_ASSERT(this->_referenceCount == 0); }
58
64 void addReference() const /*noexcept*/ {
65#ifndef NDEBUG
66 if constexpr (!isThreadSafe) {
67 CESIUM_ASSERT(std::this_thread::get_id() == this->_threadID);
68 }
69#endif
70
71 ++this->_referenceCount;
72 }
73
80 void releaseReference() const /*noexcept*/ {
81#ifndef NDEBUG
82 if constexpr (!isThreadSafe) {
83 CESIUM_ASSERT(std::this_thread::get_id() == this->_threadID);
84 }
85#endif
86
87 CESIUM_ASSERT(this->_referenceCount > 0);
88 const int32_t references = --this->_referenceCount;
89 if (references == 0) {
90 delete static_cast<const T*>(this);
91 }
92 }
93
97 std::int32_t getReferenceCount() const noexcept {
98 return this->_referenceCount;
99 }
100
101private:
102 using ThreadSafeCounter = std::atomic<std::int32_t>;
103 using NonThreadSafeCounter = std::int32_t;
104 using CounterType =
105 std::conditional_t<isThreadSafe, ThreadSafeCounter, NonThreadSafeCounter>;
106
107 mutable CounterType _referenceCount{0};
108};
109
120template <typename T>
122
133template <typename T>
135
136} // namespace CesiumUtility
A reference-counted base class, meant to be used with IntrusivePointer.
std::int32_t getReferenceCount() const noexcept
Returns the current reference count of this instance.
void releaseReference() const
Removes a counted reference from this object. When the last reference is removed, this method will de...
void addReference() const
Adds a counted reference to this object. Use CesiumUtility::IntrusivePointer instead of calling this ...
Utility classes for Cesium.
STL namespace.