tesseract  5.0.0
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  this, it.object, it.count, it.id.c_str());
47  } else {
48  delete it.object;
49  it.object = nullptr;
50  }
51  }
52  }
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 96 of file object_cache.h.

96  {
97  std::lock_guard<std::mutex> guard(mu_);
98  for (auto it = cache_.rbegin(); it != cache_.rend(); ++it) {
99  if (it->count <= 0) {
100  delete it->object;
101  cache_.erase(std::next(it).base());
102  }
103  }
104  }

◆ Free()

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

Definition at line 82 of file object_cache.h.

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

◆ Get()

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

Definition at line 60 of file object_cache.h.

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

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