Introduction
This template class implements a cache for memory objects. You can use it when you have a large collection of objects that you do not want to put entirely in memory, but you need to use some of them with quick access anyway. It can also be seen as a kind of STL map with its size controlled.
Typical use
The example below shows a cache of strings indexed by an int
:
cache<int,string> mycache;
int key=95623;
string *pText = mycache[key]; if(!mycache.iscached(pText))
{
FillTextFromDisk(key,pText); mycache.push_back(key,pText);
}
Integration
Just include cache.h in your code, copy paste the example above, and modify it following your needs as described below.
Description
cache<K, V>;
Constructor of the cache: K
is the key, and V
is the object stored. See also "Size of the cache". K
is the name of the key class; it may be a string, an int, or any object that can be a key for an STL map. V
is the name of class that you want to cache. V must support a size()
method and a correct ~V
destructor, which are used by the cache.
push_back(K k,V* p);
Insert the p
element in the cache at position k
. p
must point to a V
element or be NULL
. This element has been created with new V
, and will be deleted by the cache soon or later; this element may be NULL
, on the condition that NULL->size()
gives back 0 and delete NULL
works.
V* operator[](K& k);
This allows to access an object indexed by k
, and gives back a pointer on this object. If the object is not cached, (*V)(-1)
is returned. For example: pText = mycache[key];
.
iscached(V* p);
Simply gives back true
when p
is not -1.
Size of the cache
You can control the number of elements of the queue and the total size of the queue. A more complete declaration of the cache is:
cache<K, V, limsize>;
When the cache grows till limsize
, the older elements are removed. limsize
represents the maximum size of the cache expressed in the unit of V::size()
(for example: characters for string::size()
).
A more complete declaration of the cache is:
cache<K, V, limsize, BigQ, SmallQ>;
It allows to control the size of the queue. The size of the cache had been defined above. The size of the queue is the maximum number of V
elements allowed in the queue. When the size of the cache is greater than limsize
, SmallQ
is used, else BigQ
is used.
Hints
- Do not forget that cache will delete
V
elements. - All elements of the cache will be deleted in the destructor of the cache: do not keep it more than necessary.
- When 'maximum' is used in this article, it may be a bit more...
- It is a choice to allow or not a
NULL
pointer, but respect the conditions on V
.
V::size() { if(!this) return 0; else...
Inside
This code is based on the STL hash_map
and list
. It is not very complex once you have entered STL.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.