Patrick Audley // Code // C++ LRU Cache Template

Last Modifed (approximate)
Sun, 10 Jun 2012 12:00:00 -0700
Blackcat Systems
patrick audley, freelance hacker, technologist for hire, unix administrator, php developer, security specialist, identity analyst, chaoridx, high performance computing

C++ LRU Cache Template

Project Data
Language C++
License GPLv2
Started on
Last touched on

Fast, thread safe C++ template with Least Recently Used (LRU) removal semantics. Complete with a comprehensive unit test suite. Threading features require the BOOST scientific library to be installed.


An LRU cache is a fixed size cache that discards the oldest (least recently accessed) elements after it fills up. It's ideally suited to be used in situations where you need to speed up access to slower data sources (databases, synthetic structures, etc.). Below is a simple example of using it to cache strings using integer keys.

#include "lru_cache.h"
#include <string>
#include <iostream>

int main(void) {
	// Typedef our template for easy of readability and use.
	typedef LRUCache<int,std::string> string_cache_t;
	// Instantiate a string cache with at most three elements.
	string_cache_t *cache = new string_cache_t(3);
	// Insert data into the cache.
	std::string quote_1 = "Number is the within of all things. -Pythagoras";
	cache->insert( 4, quote_1 );

	// Fetch it out.
	std::cout << cache->fetch( 4 ) << std::endl;	

More Information

To learn more about LRU caches and caching in general, have a look at the Wikipedia page on cache algorithms for a good starting place. There is documenation and examples (in the form of unit tests) inside the distribution as well. If you really get stuck, drop me an email.

Additional Licenses

Due a few requests, I've added the GNU Affero Public License and the more commercially palettable Attribution-ShareAlike 2.5 Canada (CC BY-SA 2.5) licenses. These should allow use in most open source projects as well as commercial use with attribution.


Download Details
Direct Download
SVN Repository