Grok 20.3.2
RefCounted.h
Go to the documentation of this file.
1/*
2 * Copyright (C) 2016-2026 Grok Image Compression Inc.
3 *
4 * This source code is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU Affero General Public License, version 3,
6 * as published by the Free Software Foundation.
7 *
8 * This source code is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU Affero General Public License for more details.
12 *
13 * You should have received a copy of the GNU Affero General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *
16 */
17
18#pragma once
19
20#include <atomic>
21#include <cstdint>
22#include <stdexcept>
23
24#include "Logger.h"
25#include "grok.h"
26
27namespace grk
28{
29
30template<typename T>
31T* grk_unref(T* w)
32{
33 if(!w)
34 return nullptr;
35 grk_object_unref(&w->obj);
36 return w;
37}
38template<typename T>
39T* grk_ref(T* w)
40{
41 if(!w)
42 return nullptr;
43 grk_object_ref(&w->obj);
44 return w;
45}
46
48{
49 void operator()(void* obj) const
50 {
51 (void)obj;
52 }
53};
54
55template<typename T>
57{
58 void operator()(T* ptr) const
59 {
60 if(ptr)
61 {
62 grk_unref(ptr);
63 }
64 }
65};
66
68{
69public:
72 {
73 ++ref_count;
74 return this;
75 }
76
77 void unref()
78 {
79 if(ref_count == 0)
80 {
81 grklog.warn("Attempt to unref a released object");
82 throw std::runtime_error("Attempt to unref a released object");
83 }
84 uint32_t r = --ref_count;
85 if(r == 0)
86 {
87 delete this;
88 }
89 }
90 // Delete copy constructor and assignment operator
91 RefCounted(const RefCounted&) = delete;
92 RefCounted& operator=(const RefCounted&) = delete;
93
94protected:
95 virtual ~RefCounted() = default;
96
97private:
98 std::atomic<uint32_t> ref_count;
99};
100
101} // namespace grk
RefCounted & operator=(const RefCounted &)=delete
RefCounted(const RefCounted &)=delete
void unref()
Definition RefCounted.h:77
RefCounted * ref()
Definition RefCounted.h:71
std::atomic< uint32_t > ref_count
Definition RefCounted.h:98
virtual ~RefCounted()=default
RefCounted()
Definition RefCounted.h:70
GRK_API grk_object *GRK_CALLCONV grk_object_ref(grk_object *obj)
Increments the reference count on a Grok object.
Definition grok.cpp:340
GRK_API void GRK_CALLCONV grk_object_unref(grk_object *obj)
Decrements the reference count on a Grok object.
Definition grok.cpp:350
ResWindow.
Definition CompressedChunkCache.h:36
ILogger & grklog
Definition Logger.cpp:24
T * grk_unref(T *w)
Definition RefCounted.h:31
T * grk_ref(T *w)
Definition RefCounted.h:39
Definition RefCounted.h:48
void operator()(void *obj) const
Definition RefCounted.h:49
Definition RefCounted.h:57
void operator()(T *ptr) const
Definition RefCounted.h:58