C++ LRU Cache Template

Go to Project Site
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. I’ve also issued licenses to Fortune 500 companies, so if you need something special, contact me.