summaryrefslogtreecommitdiffstats
path: root/ComLightLib/server/RefCounter.hpp
diff options
context:
space:
mode:
authorKonstantin <const@const.me>2023-01-16 14:52:43 +0100
committerKonstantin <const@const.me>2023-01-16 14:52:43 +0100
commit8c4603c73675958efc960fbd4bb599a2909d106a (patch)
tree714dc6fc9a1672d5fd7f89676b97e10959662abc /ComLightLib/server/RefCounter.hpp
parent990a8d0dbaefc996244097397259e92758b15cce (diff)
Source codes
Diffstat (limited to 'ComLightLib/server/RefCounter.hpp')
-rw-r--r--ComLightLib/server/RefCounter.hpp38
1 files changed, 38 insertions, 0 deletions
diff --git a/ComLightLib/server/RefCounter.hpp b/ComLightLib/server/RefCounter.hpp
new file mode 100644
index 0000000..9698cc8
--- /dev/null
+++ b/ComLightLib/server/RefCounter.hpp
@@ -0,0 +1,38 @@
+#pragma once
+#include <atomic>
+#include <assert.h>
+#include <limits.h>
+
+namespace ComLight
+{
+ // Very base class of objects, implements reference counting.
+ class RefCounter
+ {
+ std::atomic_uint referenceCounter;
+
+ public:
+
+ RefCounter() : referenceCounter( 0 ) { }
+
+ inline virtual ~RefCounter() { }
+
+ RefCounter( const RefCounter &that ) = delete;
+ RefCounter( RefCounter &&that ) = delete;
+
+ protected:
+
+ uint32_t implAddRef()
+ {
+ return ++referenceCounter;
+ }
+
+ uint32_t implRelease()
+ {
+ // Might be a good idea to use locks, at least in debug builds. They're much slower than atomics, but with locks it's possible to detect when 2 threads call release at the same time, for object with counter = 1.
+ // It's a memory management bug, but it would be nice if debug builds would handle that case gracefully.
+ const uint32_t rc = --referenceCounter;
+ assert( rc != UINT_MAX );
+ return rc;
+ }
+ };
+} \ No newline at end of file