tesseract v5.3.3.20231005
tesseract::ObjectCache< T > Class Template Reference

#include <object_cache.h>

Public Member Functions

 ObjectCache ()=default
 
 ~ObjectCache ()
 
T * Get (const std::string &id, std::function< T *()> loader)
 
bool Free (T *t)
 
void DeleteUnusedObjects ()
 

Detailed Description

template<typename T>
class tesseract::ObjectCache< T >

Definition at line 36 of file object_cache.h.

Constructor & Destructor Documentation

◆ ObjectCache()

template<typename T >
tesseract::ObjectCache< T >::ObjectCache ( )
default

◆ ~ObjectCache()

template<typename T >
tesseract::ObjectCache< T >::~ObjectCache ( )
inline

Definition at line 39 of file object_cache.h.

39 {
40 std::lock_guard<std::mutex> guard(mu_);
41 for (auto &it : cache_) {
42 if (it.count > 0) {
43 tprintf(
44 "ObjectCache(%p)::~ObjectCache(): WARNING! LEAK! object %p "
45 "still has count %d (id %s)\n",
46 static_cast<void *>(this), static_cast<void *>(it.object),
47 it.count, it.id.c_str());
48 } else {
49 delete it.object;
50 it.object = nullptr;
51 }
52 }
53 }
void tprintf(const char *format,...)
Definition: tprintf.cpp:41

Member Function Documentation

◆ DeleteUnusedObjects()

template<typename T >
void tesseract::ObjectCache< T >::DeleteUnusedObjects ( )
inline

Definition at line 97 of file object_cache.h.

97 {
98 std::lock_guard<std::mutex> guard(mu_);
99 cache_.erase(std::remove_if(cache_.begin(), cache_.end(),
100 [](const ReferenceCount &it) {
101 if (it.count <= 0) {
102 delete it.object;
103 return true;
104 } else {
105 return false;
106 }
107 }),
108 cache_.end());
109 }

◆ Free()

template<typename T >
bool tesseract::ObjectCache< T >::Free ( T *  t)
inline

Definition at line 83 of file object_cache.h.

83 {
84 if (t == nullptr) {
85 return false;
86 }
87 std::lock_guard<std::mutex> guard(mu_);
88 for (auto &it : cache_) {
89 if (it.object == t) {
90 --it.count;
91 return true;
92 }
93 }
94 return false;
95 }

◆ Get()

template<typename T >
T * tesseract::ObjectCache< T >::Get ( const std::string &  id,
std::function< T *()>  loader 
)
inline

Definition at line 61 of file object_cache.h.

61 {
62 T *retval = nullptr;
63 std::lock_guard<std::mutex> guard(mu_);
64 for (auto &it : cache_) {
65 if (id == it.id) {
66 retval = it.object;
67 if (it.object != nullptr) {
68 it.count++;
69 }
70 return retval;
71 }
72 }
73 cache_.push_back(ReferenceCount());
74 ReferenceCount &rc = cache_.back();
75 rc.id = id;
76 retval = rc.object = loader();
77 rc.count = (retval != nullptr) ? 1 : 0;
78 return retval;
79 }

The documentation for this class was generated from the following file: